src/Controller/WiCamController.php line 157

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Controller\Admin\AdminOrdersController;
  4. use App\Entity\CalculationShape;
  5. use App\Entity\Customer;
  6. use App\Entity\DiameterHole;
  7. use App\Entity\FeedData;
  8. use App\Entity\FreightPricesCargo;
  9. use App\Entity\FreightPricesPackage;
  10. use App\Entity\FreightPricesTruck;
  11. use App\Entity\Holiday;
  12. use App\Entity\MaterialGrades;
  13. use App\Entity\MaterialPrices;
  14. use App\Entity\PostalCodes;
  15. use App\Entity\PriceSurcharge;
  16. use App\Entity\Representative;
  17. use App\Entity\Setting;
  18. use App\Entity\SurchargeDimensions;
  19. use App\Entity\SurchargeHandling;
  20. use App\Entity\Surcharges;
  21. use App\Entity\SurchargesCategory;
  22. use App\Entity\SurchargesHandlingCategory;
  23. use App\Entity\SurchargesThickness;
  24. use App\Entity\Thickness;
  25. use App\Entity\User;
  26. use App\Entity\UserAddress;
  27. use App\Entity\UserRepresentative;
  28. use App\Entity\WiCamFiles;
  29. use App\Entity\WiCamFilesCircles;
  30. use App\Entity\WiCamFilesPriceSurcharge;
  31. use App\Entity\WiCamFilesSurcharges;
  32. use App\Entity\WiCamFilesVariables;
  33. use App\Entity\WiCamHeader;
  34. use App\Entity\WiCamHeaderTemp;
  35. use App\Entity\WiCamHeaderNotes;
  36. use App\HttpClient\WiCamApiToken;
  37. use App\HttpClient\WiCamApiClient;
  38. use App\Repository\OrderStatusRepository;
  39. use App\Repository\SettingRepository;
  40. use App\Repository\SurchargesHandlingCategoryRepository;
  41. use App\Repository\WiCamHeaderRepository;
  42. use App\Service\DeliveryTypeService;
  43. use App\Repository\WiCamHeaderTempRepository;
  44. use App\Tools\NumberFormatter;
  45. use App\Tools\WicamApiLogHelper;
  46. use App\Tools\WicamOrderHelper;
  47. use Doctrine\ORM\EntityManagerInterface;
  48. use Doctrine\ORM\EntityRepository;
  49. use Elastica\Processor\Set;
  50. use Knp\Component\Pager\PaginatorInterface;
  51. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  52. use Symfony\Component\HttpFoundation\Request;
  53. use Symfony\Component\HttpFoundation\Response;
  54. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  55. use Symfony\Component\Mailer\MailerInterface;
  56. use Symfony\Component\Mime\Email;
  57. use Symfony\Component\Routing\Annotation\Route;
  58. use Symfony\Component\HttpFoundation\JsonResponse;
  59. use App\Service\PrintOffer;
  60. use Nzo\UrlEncryptorBundle\Encryptor\Encryptor;
  61. use PhpOffice\PhpSpreadsheet;
  62. use Symfony\Contracts\Translation\TranslatorInterface;
  63. class WiCamController extends AbstractController
  64. {
  65.     const EUR_PER_TON 1;
  66.     const EUR_PER_PIECE 2;
  67.     const EUR_EFFECTIVE_PER_FILE 3;
  68.     const EUR_EFFECTIVE_FOR_ORDER 4;
  69.     const MAX_DRILLING_DIAMETER_ID 18;
  70.     const SETTING_OFFER_TEXT 19;
  71.     const ATTEMPTS_CONNECTION 22;
  72.     const SECONDS_WAITING 23;
  73.     const DEFAULT_REPRESENTATIVE 33;
  74.     const MAX_WEIGHT_PALLET 34;
  75.     const MAX_LENGTH_PALLET 35;
  76.     const MAX_WIDTH_PALLET 37;
  77.     const MAX_HEIGHT_SHAPE 36;
  78.     const MAX_WICAM_UPLOAD_FILES 38;
  79.     const VAT_PERCENT 40;
  80.     const IN_PRICE 1;
  81.     const SEPARATED_PRICE 2;
  82.     /**
  83.      * @var WiCamApiToken
  84.      */
  85.     private $tokenClient;
  86.     /**
  87.      * @var WiCamApiClient
  88.      */
  89.     private $api_client;
  90.     /**
  91.      * @var TranslatorInterface
  92.      */
  93.     private $translator;
  94.     private $encryptor;
  95.     private $currencySymbol;
  96.     private $entityManager;
  97.     public function __construct(
  98.         WiCamApiToken       $client,
  99.         WiCamApiClient      $api_client,
  100.         WicamApiLogHelper   $apiLogHelper,
  101.         Encryptor           $encryptor,
  102.         NumberFormatter     $numberFormatter,
  103.         TranslatorInterface $translator,
  104.         EntityManagerInterface  $entityManager)
  105.     {
  106.         $this->tokenClient $client;
  107.         $this->api_client $api_client;
  108.         $this->api_client->setApiLogHelper($apiLogHelper);
  109.         $this->encryptor $encryptor;
  110.         $this->entityManager $entityManager;
  111.         if ($numberFormatter->locale == 'en') {
  112.             $this->currencySymbol '€';
  113.         } else {
  114.             $this->currencySymbol '€';
  115.         }
  116.         $this->translator $translator;
  117.     }
  118.     /**
  119.      * @Route("/upload/load-customers", name="wi_cam_load_customer")
  120.      */
  121.     public function loadCustomers(Request $request)
  122.     {
  123.         $id $request->get('id');
  124.         $customers $this->getDoctrine()->getRepository(Customer::class)->findBy(['representative' => $id]);
  125.         return $this->render('includes/select-customer.html.twig', ['customers' => $customers]);
  126.     }
  127.     /**
  128.      * @Route("/upload", name="wi_cam_home")
  129.      * @Route("/admin/upload", name="wi_cam_admin_home")
  130.      * @param Request $request
  131.      *
  132.      * @return Response
  133.      */
  134.     public function index(Request $request)
  135.     {
  136.         $idEdit $request->get('id');
  137.         $thickness $this->getDoctrine()->getRepository(Thickness::class)->findBy(['active' => 1], ['value' => 'ASC']);
  138.         $materialgrades $this->getDoctrine()->getRepository(MaterialGrades::class)->findBy(['active' => true]);
  139.         $pricessurcharges $this->getDoctrine()->getRepository(PriceSurcharge::class)->findAll();
  140.         $surcharges $this->getDoctrine()->getRepository(Surcharges::class)->findBy(['active' => 1'allow_to_apply_all' => 1]);
  141.         $shapes $this->getDoctrine()->getRepository(CalculationShape::class)->findBy(['active' => 1], ['orden' => 'ASC']);
  142.         /** @var Setting $maxUploadFiles */
  143.         $maxUploadFiles $this->getDoctrine()->getRepository(Setting::class)->find(self::MAX_WICAM_UPLOAD_FILES);
  144.         /** @var EntityRepository $repository */
  145.         $repository $this->getDoctrine()->getRepository(CalculationShape::class);
  146.         $qb $repository->createQueryBuilder('cs');
  147.         $customers null;
  148.         $user $this->getUser();
  149.         $isLoggedIn $user true false;
  150.         $qbT $qb
  151.             ->select('DISTINCT cs')
  152.             ->from('App\Entity\WiCamFiles''wf')
  153.             ->from('App\Entity\WiCamHeader''wh')
  154.             ->AndWhere('cs.id = wf.CalculationShape ')
  155.             ->AndWhere('wf.wicam_header = wh.id ')
  156.             ->AndWhere('wf.deleted = 0')
  157.             ->AndWhere('cs.active IN(1,15)')
  158.             ->orderBy('cs.orden''ASC');
  159.         if ($user) {
  160.             if ($this->isGranted('ROLE_REPRESENTATIVE')) {
  161.                 /** @var Representative $representative */
  162.                 $representative $user->getUserRepresentatives()->get(0)->getRepresentative();
  163.                 $qbT->andWhere('wh.representative = :representative ')
  164.                     ->setParameter('representative'$representative->getId());
  165.                 $customers $representative->getCustomers();
  166.             }
  167.         }
  168.         $shapesFrequently $qbT->getQuery()
  169.             ->getResult();
  170.         /** @var WiCamHeader $wicamHeader */
  171.         $wicamHeader null;
  172.         $countWicamFiles false;
  173.         /** @var WiCamHeaderTemp $wicamHTemp */
  174.         $wicamHTemp null;
  175.         $plz null;
  176.         $filesHtml '';
  177.         $isRepresentativeOrAdmin $this->isGranted('ROLE_REPRESENTATIVE') || $this->isGranted('ROLE_ADMIN');
  178.         $toEdit false;
  179.         $notes = [];
  180.         $representatives null;
  181.         if (!empty($idEdit)) {
  182.             $wsCode $idEdit;
  183.             $wicamHeader $this->getDoctrine()->getRepository(WiCamHeader::class)->find($wsCode);
  184.              //Create temporal wicamHeader in the same table oc_wicam_header (temporal = 1)
  185.             $em $this->getDoctrine()->getManager();
  186.             $wicamHeaderTemporal = new WiCamHeaderTemp();
  187.             $wicamHeaderTemporal->setDateSurcharge($wicamHeader->getDateSurcharge());
  188.             $wicamHeaderTemporal->setGuid($wicamHeader->getGuid());
  189.             if(is_int((int)$wicamHeader->getPlz())){
  190.                 $wicamHeaderTemporal->setPlz($wicamHeader->getPlz());
  191.             } else {
  192.                 $wicamHeaderTemporal->setPlz(0);
  193.             }
  194.             $wicamHeaderTemporal->setPriceSurchargeId($wicamHeader->getPriceSurcharge()->getId());
  195.             $wicamHeaderTemporal->setDeliveryType($wicamHeader->getDeliveryType());
  196.             $wicamHeaderTemporal->setDeliveryCost($wicamHeader->getDeliveryCost());
  197.             $wicamHeaderTemporal->setGeneralTotalPrice($wicamHeader->getGeneralTotalPrice());
  198.             $wicamHeaderTemporal->setSurchargesTotal($wicamHeader->getSurchargesTotal());
  199.             $wicamHeaderTemporal->setVatPercent($wicamHeader->getVatPercent());
  200.             if(!empty($wicamHeader->getVatPercentTotal())){
  201.                 $wicamHeaderTemporal->setVatPercentTotal($wicamHeader->getVatPercentTotal());
  202.             } else {
  203.                 $wicamHeaderTemporal->setVatPercentTotal("0");
  204.             }
  205.             $wicamHeaderTemporal->setGeneralTotal($wicamHeader->getGeneralTotal());
  206.             $wicamHeaderTemporal->setIsOrder($wicamHeader->getIsOrder());
  207.             $wicamHeaderTemporal->setOrderNumber($wicamHeader->getOrderNumber());
  208.             $wicamHeaderTemporal->setDateOrder($wicamHeader->getDateOrder());
  209.             $wicamHeaderTemporal->setRepresentativeId($wicamHeader->getRepresentative()->getId());
  210.             if(!empty($wicamHeader->getCustomer())){
  211.                 $wicamHeaderTemporal->setCustomerId($wicamHeader->getCustomer()->getId());
  212.             } else {
  213.                 $wicamHeaderTemporal->setCustomerId(null);
  214.             }
  215.             $wicamHeaderTemporal->setOrderStatusId($wicamHeader->getOrderStatus()->getId());
  216.             $wicamHeaderTemporal->setOrderStatusDateChanged($wicamHeader->getOrderStatusDateChanged());
  217.             $wicamHeaderTemporal->setDeleted($wicamHeader->getDeleted());
  218.             $wicamHeaderTemporal->setDateSys($wicamHeader->getDateSys());
  219.             $wicamHeaderTemporal->setWicamHeaderId($wicamHeader->getId());
  220.             $em->persist($wicamHeaderTemporal);
  221.             $em->flush();
  222.             $idTemporal $wicamHeaderTemporal->getId();
  223.             $wicamHTemp $this->getDoctrine()->getRepository(WiCamHeaderTemp::class)->find($idTemporal);
  224.             $countWicamFiles $wicamHeader->getCountActiveWicamFiles() > 0;
  225.             $filesHtml $this->GetFileResponse($wicamHeader$thickness$materialgrades$pricessurcharges);
  226.             $plz $this->getDoctrine()->getRepository(PostalCodes::class)->findOneBy(['plz' => $wicamHeader->getPlz()]);
  227.             $toEdit true;
  228.             $notes $this->getDoctrine()->getRepository(WiCamHeaderNotes::class)->findBy(['flag' => 1'wicam_header' => $wicamHeader->getId()]);
  229.             if ($this->isGranted('ROLE_ADMIN')) {
  230.                 $representatives $this->getDoctrine()->getRepository(Representative::class)->findAll();
  231.                 if (!empty($wicamHTemp->getRepresentativeId())) {
  232.                     $representative $wicamHTemp->getRepresentativeId();
  233.                     $customers $this->getDoctrine()->getRepository(Representative::class)->find($representative)->getCustomers();
  234.                 }
  235.             }
  236.         } else {
  237.             if (isset($_COOKIE['wsCode'])) {
  238.                 $wsCode $_COOKIE['wsCode'];
  239.                 if (!empty($wsCode)) {
  240.                     if (is_numeric($wsCode)) {
  241.                         $wsCodeEn $this->encryptor->encrypt($wsCode);
  242.                         setcookie('wsCode'$wsCodeEntime() + 604800'/');
  243.                     } else {
  244.                         $wsCode $this->encryptor->decrypt($wsCode);
  245.                     }
  246.                     $wicamHeader $this->getDoctrine()->getRepository(WiCamHeader::class)->find($wsCode);
  247.                     // if the offer in the cookie doesnt have representative assigned then it can show but it has representative assigned then should check if the representative
  248.                     // is the same that the user logged.
  249.                     $countWicamFiles $wicamHeader->getCountActiveWicamFiles() > 0;
  250.                     if ($wicamHeader->getIsOrder()) {
  251.                         $wicamHeader null;
  252.                         setcookie("wsCode"""time() - 3600'/');
  253.                     } elseif (empty($wicamHeader->getRepresentative())) {
  254.                         if ($this->getUser()) {
  255.                             /** @var User $user */
  256.                             $user $this->getUser();
  257.                             if ($this->isGranted('ROLE_REPRESENTATIVE')) {
  258.                                 /** @var UserRepresentative $userRepresentative */
  259.                                 $userRepresentative $user->getUserRepresentatives()->get(0);
  260.                                 $wicamHeader->setRepresentative($userRepresentative->getRepresentative());
  261.                                 $this->getDoctrine()->getManager()->flush();
  262.                             } elseif ($this->isGranted('ROLE_USER')) { // if it is customer login
  263.                                 $activeCustomer $user->getActiveCustomerForUserCustomer();
  264.                                 $arrayAddress $this->getArrayAddress($user);
  265.                                 $wicamHeader->setCustomer($activeCustomer);
  266.                                 $wicamHeader->setPlz($arrayAddress['plz']);
  267.                                 $wicamHeader->setCity($arrayAddress['city']);
  268.                                 $wicamHeader->setCountry($arrayAddress['country']);
  269.                                 $wicamHeader->setStreet($arrayAddress['street']);
  270.                                 $wicamHeader->setRepresentative($activeCustomer->getRepresentative());
  271.                                 $this->getDoctrine()->getManager()->flush();
  272.                             }
  273.                         }
  274.                         $filesHtml $this->GetFileResponse($wicamHeader$thickness$materialgrades$pricessurcharges);
  275.                         $plz $this->getDoctrine()->getRepository(PostalCodes::class)->findOneBy(array('plz' => $wicamHeader->getPlz()));
  276.                     } else {
  277.                         if ($this->getUser()) {
  278.                             /** @var User $user */
  279.                             $user $this->getUser();
  280.                             if ($this->isGranted('ROLE_REPRESENTATIVE')) {
  281.                                 /** @var UserRepresentative $userRepresentative */
  282.                                 $userRepresentative $user->getUserRepresentatives()->get(0);
  283.                                 if ($wicamHeader->getRepresentative()->getId() == $userRepresentative->getRepresentative()->getId()) {
  284.                                     $filesHtml $this->GetFileResponse($wicamHeader$thickness$materialgrades$pricessurcharges);
  285.                                     $plz $this->getDoctrine()->getRepository(PostalCodes::class)->findOneBy(array('plz' => $wicamHeader->getPlz()));
  286.                                 }
  287.                             } elseif ($this->isGranted('ROLE_USER')) { // if it is customer login
  288.                                 $activeCustomer $user->getActiveCustomerForUserCustomer();
  289.                                 $arrayAddress $this->getArrayAddress($user);
  290.                                 $wicamHeader->setCustomer($activeCustomer);
  291.                                 $wicamHeader->setRepresentative($activeCustomer->getRepresentative());
  292.                                 $wicamHeader->setPlz($arrayAddress['plz']);
  293.                                 $wicamHeader->setCity($arrayAddress['city']);
  294.                                 $wicamHeader->setCountry($arrayAddress['country']);
  295.                                 $wicamHeader->setStreet($arrayAddress['street']);
  296.                                 $this->getDoctrine()->getManager()->flush();
  297.                                 $filesHtml $this->GetFileResponse($wicamHeader$thickness$materialgrades$pricessurcharges);
  298.                                 $plz $this->getDoctrine()->getRepository(PostalCodes::class)->findOneBy(array('plz' => $wicamHeader->getPlz()));
  299.                             } else {
  300.                                 $wicamHeader null;
  301.                                 setcookie("wsCode"""time() - 3600'/');
  302.                             }
  303.                         } else {
  304.                             $wicamHeader null;
  305.                             setcookie("wsCode"""time() - 3600'/');
  306.                         }
  307.                     }
  308.                 }
  309.             }
  310.         }
  311.         return $this->render('wicam/index.html.twig', [
  312.             'isLoggedIn'              => $isLoggedIn,
  313.             'isRepresentativeOrAdmin' => $isRepresentativeOrAdmin,
  314.             'thickness'               => $thickness,
  315.             'materialgrades'          => $materialgrades,
  316.             'pricessurcharges'        => $pricessurcharges,
  317.             'surcharges_items'        => $surcharges,
  318.             'shapes'                  => $shapes,
  319.             'shapesFrequently'        => $shapesFrequently,
  320.             'guid'                    => uniqid(),
  321.             'WH'                      => $wicamHTemp,
  322.             'plz'                     => $plz,
  323.             'files'                   => $filesHtml,
  324.             'toEdit'                  => $toEdit,
  325.             'notes'                   => $notes,
  326.             'customers'               => $customers,
  327.             'representatives'         => $representatives,
  328.             'maxUploadFiles'          => $maxUploadFiles->getValue(),
  329.             'general_setting_box'     => $countWicamFiles
  330.         ]);
  331.     }
  332.     private function GetFileResponse(WiCamHeader $WH$thickness$materialgrades$prices_surcharge)
  333.     {
  334.         $entityManager $this->getDoctrine()->getManager();
  335.         $surcharges $entityManager->getRepository(Surcharges::class)->findBy(['active' => 1]);
  336.         $wicamFiles $entityManager->getRepository(WiCamFiles::class)->findBy(['deleted' => 0'validation' => 1'wicam_header' => $WH->getId()], ['orden' => 'ASC']);
  337.         $response = [];
  338.         /** @var WiCamFiles $wf */
  339.         foreach ($wicamFiles as $wf) {
  340.             $key $wf->getId();
  341.             $circles = [];
  342.             /** @var WiCamFilesCircles $wfc */
  343.             if (!empty($wf->getWiCamFilesCircles())) {
  344.                 foreach ($wf->getWiCamFilesCircles() as $wfc) {
  345.                     $circle['diameter'] = $wfc->getDiameter();
  346.                     $circle['amount'] = $wfc->getAmount();
  347.                     $thickness_value 0;
  348.                     if ($wf->getThickness() != null) {
  349.                         $thickness_value $wf->getThickness()->getValue();
  350.                     }
  351.                     $diameters $this->getDoctrine()->getRepository(DiameterHole::class)->findByThicknessAmount($thickness_value$wfc->getAmount());
  352.                     //$html_diameters =   $this->renderView('includes/wicam-diameter-hole.html.twig',['diameters'=>$diameters]);
  353.                     $circle['diameters'] = $diameters;
  354.                     $circle['wfc'] = $wfc;
  355.                     $circles[] = $circle;
  356.                 }
  357.             }
  358.             $basicInformation = ['width' => $wf->getWidth(), 'length' => $wf->getLength()];
  359.             $extendedInformation = [
  360.                 'contour' => ['total' => $wf->getContours()],
  361.                 'length'  => ['total' => $wf->getTotalLenght()],
  362.                 'area'    => ['geometry' => $wf->getPartNetArea()],
  363.                 'circles' => $circles
  364.             ];
  365.             $isShape $wf->getIsShape();
  366.             if ($isShape) {
  367.                 $CalculationShape $wf->getCalculationShape();
  368.                 $response[$key]['name'] = $CalculationShape->getDescription();
  369.                 $response[$key]['CalculationShape'] = $CalculationShape;
  370.                 $WiCamFilesVariables $this->getDoctrine()->getRepository(WiCamFilesVariables::class)->findBy(['wicam_files' => $wf->getId()]);
  371.                 $response[$key]['WiCamFilesVariables'] = $WiCamFilesVariables;
  372.             } else {
  373.                 $response[$key]['name'] = $wf->getName();
  374.             }
  375.             $response[$key]['isShape'] = $isShape;
  376.             $response[$key]['identify'] = $wf->getId();
  377.             $response[$key]['is_valid'] = true;
  378.             $response[$key]['invalid_reason'] = '';
  379.             $response[$key]['validation'] = "";
  380.             $response[$key]['information'] = [];
  381.             $response[$key]['image'] = base64_decode($wf->getSvgFile());
  382.             $response[$key]['wicam'] = $wf;
  383.             $response[$key]['information'] = [
  384.                 'basicInformation'    => $basicInformation,
  385.                 'extendedInformation' => $extendedInformation
  386.             ];
  387.             $response[$key]['res'] = ['fileId' => $wf->getWicamId()];
  388.         }
  389.         $responseFiles['thickness'] = $thickness;
  390.         $responseFiles['materialgrades'] = $materialgrades;
  391.         $responseFiles['prices_surcharges'] = $prices_surcharge;
  392.         $responseFiles['countFiles'] = count($response);
  393.         $responseFiles['files'] = $response;
  394.         $responseFiles['surcharges'] = $surcharges;
  395.         $validation_errors = [];
  396.         /** @var Setting $setting */
  397.         $setting $this->getDoctrine()->getManager()->getRepository(Setting::class)->find(self::MAX_DRILLING_DIAMETER_ID);
  398.         /** @var Setting $maxHeightShape */
  399.         $maxHeightShape $this->getDoctrine()->getManager()->getRepository(Setting::class)->find(self::MAX_HEIGHT_SHAPE);
  400.         $isRepresentativeOrAdmin $this->isGranted('ROLE_REPRESENTATIVE') || $this->isGranted('ROLE_ADMIN');
  401.         $html $this->renderView('wicam/files.html.twig', [
  402.             'responseFiles'           => $responseFiles,
  403.             'errors'                  => $validation_errors,
  404.             'MAX_DRILLING_DIAMETER'   => $setting->getValue(),
  405.             'maxHeightShape'          => $maxHeightShape,
  406.             'isRepresentativeOrAdmin' => $isRepresentativeOrAdmin
  407.         ]);
  408.         return $html;
  409.     }
  410.     /**
  411.      * @Route("/upload/file",  methods={"POST"}, name="wi_cam_upload")
  412.      * @param Request $request
  413.      *
  414.      * @return JsonResponse
  415.      */
  416.     public function upload_file(Request $request)
  417.     {
  418.         /*return new Response(
  419.             var_export($request,true)
  420.         );*/
  421.         $file $request->files->get('file');
  422.         $filenames = [];
  423.         foreach ($file as $fl) {
  424.             if (strtolower($fl->getClientOriginalExtension()) == 'dxf' || strtolower($fl->getClientOriginalExtension()) == 'dwg') {
  425.                 $fileName uniqid() . '.' $fl->getClientOriginalExtension();
  426.                 $realName $fl->getClientOriginalName();
  427.                 $uploadFile $fl->move(
  428.                     $this->getParameter('uploaded_image_directory'),
  429.                     $fileName
  430.                 );
  431.                 $filenames[] = ['name' => $fileName'realname' => $realName];
  432.             }
  433.         }
  434.         $html $this->renderView('includes/wicam-list-files.html.twig', [
  435.             'responseFiles' => $filenames
  436.         ]);
  437.         $response = ['filenames' => $filenames'html' => $html];
  438.         return new JsonResponse($response);
  439.     }
  440.     /**
  441.      * @Route("/upload/generate",  methods={"POST"}, name="wi_cam_generate")
  442.      * @param Request $request
  443.      *
  444.      * @return JsonResponse
  445.      */
  446.     public function GenerateHeader(Request $requestOrderStatusRepository $orderStatusRepository)
  447.     {
  448.         $guid $request->get("guid");
  449.         $manager $this->getDoctrine()->getManager();
  450.         /** @var WiCamHeader $wicamheader */
  451.         $wicamheader = new WiCamHeader();
  452.         $wicamheader->setGuid($guid);
  453.         $wicamheader->setPlz("");
  454.         $wicamheader->setOrderStatus($orderStatusRepository->find(1));
  455.         /** @var User $user */
  456.         $user $this->getUser();
  457.         if ($user) {
  458.             if ($this->isGranted('ROLE_REPRESENTATIVE')) {
  459.                 /** @var UserRepresentative $userRepresentative */
  460.                 $userRepresentative $user->getUserRepresentatives()->get(0);
  461.                 $wicamheader->setRepresentative($userRepresentative->getRepresentative());
  462.             } elseif ($this->isGranted('ROLE_USER')) {
  463.                 $activeCustomer $user->getActiveCustomerForUserCustomer();
  464.                 $wicamheader->setCustomer($activeCustomer);
  465.                 $wicamheader->setRepresentative($activeCustomer->getRepresentative());
  466.             } else {
  467.                 $wicamHeader null;
  468.                 setcookie("wsCode"""time() - 3600'/');
  469.             }
  470.         }
  471.         $manager->persist($wicamheader);
  472.         $manager->flush();
  473.         setcookie('wsCode'$this->encryptor->encrypt($wicamheader->getId()), time() + 604800'/');
  474.         return new JsonResponse(array('id' => $wicamheader->getId()));
  475.     }
  476.     /**
  477.      * @Route("/upload/set_header",  methods={"POST"}, name="wi_cam_set_header")
  478.      * @param Request $request
  479.      *
  480.      * @return JsonResponse
  481.      * @throws \Exception
  482.      */
  483.     public function SetHeader(Request $request): JsonResponse
  484.     {
  485.         $header_id $request->get("header_id");
  486.         $date_surcharge $request->get("date_surcharge");
  487.         $ps $request->get("ps");
  488.         $manager $this->getDoctrine()->getManager();
  489.         /** @var WiCamHeader $wicamheader */
  490.         $wicamheader $manager->getRepository(WiCamHeader::class)->find($header_id);
  491.         /** @var PriceSurcharge $price_surcharge */
  492.         $price_surcharge $manager->getRepository(PriceSurcharge::class)->find($ps);
  493.         if (empty($date_surcharge)) {
  494.             $wicamheader->setDateSurcharge(null);
  495.             $wicamheader->setPriceSurcharge(null);
  496.         } else {
  497.             $wicamheader->setDateSurcharge(new \DateTime($date_surcharge));
  498.             $wicamheader->setPriceSurcharge($price_surcharge);
  499.         }
  500.         $manager->flush();
  501.         return new JsonResponse(array('id' => $wicamheader->getId()));
  502.     }
  503.     /**
  504.      * @Route("/upload/send",  methods={"POST"}, name="wi_cam_send")
  505.      * @param Request $request
  506.      *
  507.      * @return JsonResponse
  508.      */
  509.     public function send_file(Request $requestSettingRepository $settingRepository)
  510.     {
  511.         $token $this->GetToken($request);
  512.         $files $request->get("files");
  513.         $guid $request->get("guid");
  514.         $header_id $request->get("header_id");
  515.         $manager $this->getDoctrine()->getManager();
  516.         /** @var Setting $setting */
  517.         $setting $manager->getRepository(Setting::class)->find(14);
  518.         $minimal_length $setting->getValue() * 1.0;
  519.         $setting $manager->getRepository(Setting::class)->find(15);
  520.         $maximal_length $setting->getValue() * 1.0;
  521.         $setting $manager->getRepository(Setting::class)->find(16);
  522.         $minimal_width $setting->getValue() * 1.0;
  523.         $setting $manager->getRepository(Setting::class)->find(17);
  524.         $maximal_width $setting->getValue() * 1.0;
  525.         $thickness $this->getDoctrine()->getRepository(Thickness::class)->findBy(['active' => 1], ['value' => 'ASC']);
  526.         $materialgrades $this->getDoctrine()->getRepository(MaterialGrades::class)->findBy(['active' => true]);
  527.         /** @var MaterialGrades $mg */
  528.         $mg null;
  529.         if (count($materialgrades) == 1) {
  530.             $mg $materialgrades[0];
  531.         }
  532.         $surcharges $this->getDoctrine()->getRepository(Surcharges::class)->findBy(['active' => 1]);
  533.         $prices_surcharge $this->getDoctrine()->getRepository(PriceSurcharge::class)->findAll();
  534.         /** @var Setting $setting */
  535.         $setting $settingRepository->find(self::MAX_DRILLING_DIAMETER_ID);
  536.         $canProduceDrillings $this->getParameter('can_produce_drillings');
  537.         $finalFiles = [];
  538.         foreach ($files as $fl) {
  539.             $finalFiles[] = [
  540.                 'filename' => $this->getParameter('uploaded_image_directory') . '/' $fl['realName'],
  541.                 'name'     => $fl['fileName']
  542.             ];
  543.         }
  544.         /** @var WiCamHeader $wicamheader */
  545.         $wicamheader $this->getDoctrine()->getRepository(WiCamHeader::class)->find($header_id);
  546.         $response $this->api_client->sendFiles($token$finalFiles);
  547.         $validation_errors = [];
  548.         if ($response) {
  549.             foreach ($response as $key => $rp) {
  550.                 $invalid_reason '';
  551.                 $file_id $rp['res']['fileId'];
  552.                 $collectionID $rp['res']['collectionId'];
  553.                 $fileInformation '';
  554.                 $fileInformation $this->GetInformationFile($token$file_id$collectionID);
  555.                 $validation '';
  556.                 sleep(1);
  557.                 $image $this->getImage($token$file_id$collectionID);
  558.                 $ct 1;
  559.                 while ($image['status'] <> 200 && $ct <= 5) {
  560.                     sleep(1);
  561.                     $image $this->getImage($token$file_id$collectionID);
  562.                     $ct++;
  563.                 }
  564.                 $pngImage $this->getImagePng($token$file_id$collectionID);
  565.                 $pngImage base64_encode($pngImage['image']);
  566.                 $validation $this->InternalValidation($fileInformation);
  567.                 $validation_errors $validation[1];
  568.                 $validation $validation[0];
  569.                 $response[$key]['validation'] = $validation;
  570.                 $response[$key]['information'] = $fileInformation;
  571.                 $response[$key]['image'] = ($image['image']);
  572.                 /** @var WiCamFiles $WiCamFile */
  573.                 $WiCamFile = new WiCamFiles();
  574.                 $is_valid $validation == 'Valid' '1' '0';
  575.                 $w $fileInformation['basicInformation']['width'];
  576.                 $l $fileInformation['basicInformation']['length'];
  577.                 $is_valid_l true;
  578.                 $is_valid_w true;
  579.                 $is_valid_lmin true;
  580.                 $is_valid_lmax true;
  581.                 $is_valid_wmin true;
  582.                 $is_valid_wmax true;
  583.                 if ($minimal_length >= || $maximal_length || $minimal_width >= || $maximal_width 0) {
  584.                     $is_valid_l $is_valid_lmin = ($l >= $minimal_length);
  585.                     if ($maximal_length 0) {
  586.                         $is_valid_lmax $l <= $maximal_length;
  587.                         $is_valid_l $is_valid_lmin && $is_valid_lmax;
  588.                     }
  589.                     $is_valid_w $is_valid_wmin = ($w >= $minimal_width);
  590.                     if ($maximal_width 0) {
  591.                         $is_valid_wmax $w <= $maximal_width;
  592.                         $is_valid_w $is_valid_wmin && $is_valid_wmax;
  593.                     }
  594.                 }
  595.                 if (!$is_valid_l || !$is_valid_w) {
  596.                     if (!$is_valid_lmin || !$is_valid_wmin) {
  597.                         $msgInvalid "Ein min. Wert wird unterschritten: <br>
  598.                         Das von Ihnen eingelesene Bauteil unterschreitet das Mindestmaß (min. Bauteilgröße: %minimalLength% x %minimalWidth% mm). 
  599.                         <br><br> Bitte fragen Sie größere Abmessungen unter <a href='mailto:info@cad2cut.de'>info@cad2cut.de</a> an.";
  600.                         $invalid_reason .= "\n" $this->translator->trans($msgInvalid, ['%minimalWidth%' => $minimal_width'%minimalLength%' => $minimal_length]);
  601.                     }
  602.                     if (!$is_valid_lmax || !$is_valid_wmax) {
  603.                         $msgInvalid "Ein max. Wert wird überschritten: <br>
  604.                         Das von Ihnen eingelesene Bauteil überschreitet die maximal mögliche Abmessung  (max. Bauteilgröße: %maximalLength% x %maximalWidth% mm). 
  605.                         <br><br> Bitte fragen Sie größere Abmessungen unter <a href='mailto:info@cad2cut.de'>info@cad2cut.de</a> an.";
  606.                         $invalid_reason .= "\n" $this->translator->trans($msgInvalid, ['%maximalWidth%' => $maximal_width'%maximalLength%' => $maximal_length]);
  607.                     }
  608.                     $is_valid '0';
  609.                 }
  610.                 /** @var WiCamFilesCircles $WiCamCircle */
  611.                 if ($fileInformation['extendedInformation']['circles']) {
  612.                     $circles 0;
  613.                     foreach ($fileInformation['extendedInformation']['circles'] as $circle) {
  614.                         if ($circle['diameter'] <= $setting->getValue()) {
  615.                             $circles++;
  616.                         } else {
  617.                             $is_valid '0';
  618.                             $validation 'Invalid File<br>Has circles with diameter not allowed.<br>';
  619.                             $invalid_reason 'Has circles with diameter not allowed.';
  620.                         }
  621.                         $WiCamCircle = new WiCamFilesCircles();
  622.                         $WiCamCircle->setWicamFiles($WiCamFile)
  623.                             ->setDiameter($circle['diameter'])
  624.                             ->setAmount($circle['amount']);
  625.                         $manager->persist($WiCamCircle);
  626.                     }
  627.                     if (!$canProduceDrillings && $circles 0) {
  628.                         $is_valid '0';
  629.                         $validation 'Invalid File<br>Has circles<br>';
  630.                         $invalid_reason 'Has circles';
  631.                     }
  632.                     if ($circles 0) {
  633.                         $WiCamFile->setHasCircles(true);
  634.                     } else {
  635.                         $WiCamFile->setHasCircles(false);
  636.                     }
  637.                 } else {
  638.                     $WiCamFile->setHasCircles(false);
  639.                 }
  640.                 $WiCamFile->setWicamId($file_id)
  641.                     ->setName($fileInformation['file']['name'])
  642.                     ->setCollectionID($collectionID)
  643.                     ->setOriginalName($fileInformation['file']['name'])
  644.                     ->setGeometryName("")
  645.                     ->setExtension($fileInformation['file']['extension'])
  646.                     ->setLength($fileInformation['basicInformation']['length'])
  647.                     ->setWidth($fileInformation['basicInformation']['width'])
  648.                     ->setPartNetArea($fileInformation['extendedInformation']['area']['geometry'])
  649.                     ->setContours($fileInformation['extendedInformation']['contour']['total'])
  650.                     ->setTotalLenght($fileInformation['extendedInformation']['length']['total'])
  651.                     ->setValidationInfo($validation)
  652.                     ->setValidation($is_valid)
  653.                     ->setPngFile($pngImage)
  654.                     ->setSvgFile(base64_encode($image['image']))
  655.                     ->setDeleted(false)
  656.                     ->setGuid($guid)
  657.                     ->setIsShape(false)
  658.                     ->setWiCamHeader($wicamheader);
  659.                 if (!empty($mg)) {
  660.                     $WiCamFile->setMaterialGrades($mg);
  661.                 }
  662.                 $WiCamFile->setJson(json_encode($fileInformation));
  663.                 $manager->persist($WiCamFile);
  664.                 $manager->flush();
  665.                 $response[$key]['identify'] = $WiCamFile->getId();
  666.                 $response[$key]['wicam'] = $WiCamFile;
  667.                 $response[$key]['isShape'] = false;
  668.                 $response[$key]['is_valid'] = $is_valid;
  669.                 $response[$key]['invalid_reason'] = $invalid_reason;
  670.             }
  671.         }
  672.         $responseFiles['thickness'] = $thickness;
  673.         $responseFiles['materialgrades'] = $materialgrades;
  674.         $responseFiles['prices_surcharges'] = $prices_surcharge;
  675.         $responseFiles['countFiles'] = count($response);
  676.         $responseFiles['files'] = $response;
  677.         $responseFiles['surcharges'] = $surcharges;
  678.         //echo '<pre>'; var_dump($response); die;
  679.         /*return $this->render('wicam/files.html.twig', [
  680.             'responseFiles' => $responseFiles
  681.         ]);*/
  682.         /** @var Setting $maxHeightShape */
  683.         $maxHeightShape $settingRepository->find(self::MAX_HEIGHT_SHAPE);
  684.         $isRepresentativeOrAdmin $this->isGranted('ROLE_REPRESENTATIVE') || $this->isGranted('ROLE_ADMIN');
  685.         $html $this->renderView('wicam/files.html.twig', [
  686.             'responseFiles' => $responseFiles,
  687.             'errors' => $validation_errors,
  688.             'MAX_DRILLING_DIAMETER' => $setting->getValue(),
  689.             'maxHeightShape' =>  $maxHeightShape,
  690.             'isRepresentativeOrAdmin' => $isRepresentativeOrAdmin
  691.         ]);
  692.         $html_invalid_files $this->renderView('includes/wicam-invalid-files.html.twig', [
  693.             'responseFiles' => $responseFiles,
  694.             'errors'        => $validation_errors
  695.         ]);
  696.         $response_ar = array('html' => $html'errors' => $validation_errors'header_id' => $wicamheader->getId(), 'html_invalid_files' => $html_invalid_files);
  697.         return new JsonResponse($response_ar);
  698.     }
  699.     /**
  700.      * @Route("/upload/validate",  methods={"POST"}, name="wi_cam_validate")
  701.      * @param Request $request
  702.      *
  703.      * @return Response
  704.      */
  705.     public function Validate(Request $request)
  706.     {
  707.         $token $this->GetToken($request);
  708.         $id $request->get("id");
  709.         $htmlResponse $this->InternalValidation($token$id);
  710.         return new Response($htmlResponse);
  711.     }
  712.     function InternalValidation($fileInformation)
  713.     {
  714.         $errors[50001] = 'Open contour';
  715.         $errors[50002] = 'Double contour';
  716.         $errors[50003] = 'Part in part';
  717.         $errors[50004] = 'No geometry found';
  718.         $errors[50005] = 'Overlapping lines';
  719.         $errors[50006] = 'Open outer contour';
  720.         $errors[50007] = 'Inner contour collides with outer contour';
  721.         $validation $fileInformation['validation'];
  722.         if (empty($validation['geometryErrors'])) {
  723.             $htmlResponse 'Valid';
  724.         } else {
  725.             $htmlResponse 'Invalid File<br>';
  726.             if ($validation['geometryErrors']) {
  727.                 foreach ($validation['geometryErrors'] as $er) {
  728.                     $code $er['code'];
  729.                     $code = (int)$code;
  730.                     $htmlResponse .= '' $errors[$code] . '<br>';
  731.                     $htmlResponse .= '<b>X:</b>' $er['x'] . '&nbsp;&nbsp;';
  732.                     $htmlResponse .= '<b>Y:</b>' $er['y'] . '<br>';
  733.                     //$htmlResponse .= ''.$errors[$er].'<br>';
  734.                 }
  735.             }
  736.         }
  737.         return [$htmlResponse$validation['geometryErrors']];
  738.     }
  739.     function GetInformationFile($token$id$collectionId)
  740.     {
  741.         $entityManager $this->getDoctrine()->getManager();
  742.         $attemps $entityManager->getRepository(Setting::class)->find(self::ATTEMPTS_CONNECTION);
  743.         $attemps $attemps->getValue();
  744.         $seconds $entityManager->getRepository(Setting::class)->find(self::SECONDS_WAITING);
  745.         $seconds $seconds->getValue();
  746.         return $this->api_client->FileInformation($token$id$collectionId$attemps$seconds);
  747.         /* $htmlResponse = '';
  748.          $htmlResponse .= '<b>length:</b>&nbsp;<span class="length">'.$response['length'].'</span><br>';
  749.          $htmlResponse .= '<b>width:</b>&nbsp;<span class="width">'.$response['width'].'</span><br>';
  750.          $htmlResponse .= '<b>partNetArea:</b>&nbsp;<span class="partNetArea">'.$response['partNetArea'].'</span><br>';
  751.          $htmlResponse .= '<b>partArea:</b>&nbsp;'.$response['partArea'].'<br>';
  752.          $htmlResponse .= '<b>closedInnerContours:</b>&nbsp;'.$response['closedInnerContours'];
  753.         return $htmlResponse;*/
  754.     }
  755.     /**
  756.      * @Route("/upload/download",  methods={"POST"}, name="wi_cam_download")
  757.      * @param Request $request
  758.      *
  759.      * @return JsonResponse
  760.      */
  761.     public function Download(Request $request)
  762.     {
  763.         $token $this->GetToken($request);
  764.         $id $request->get("id");
  765.         $response $this->api_client->DownloadFile($token$id);
  766.         //sleep(1);
  767.         $fileInformation $this->GetInformationFile($token$id);
  768.         $finalResponse = [
  769.             'image'       => $response,
  770.             'information' => $fileInformation
  771.         ];
  772.         return new JsonResponse($finalResponse);
  773.     }
  774.     /**
  775.      * @Route("/upload/calculate",  methods={"POST"}, name="wi_cam_calculate")
  776.      * @param Request $request
  777.      *
  778.      * @return JsonResponse
  779.      */
  780.     public function Calculate(Request $request): JsonResponse
  781.     {
  782.         $plz $request->get('plz');
  783.         $customer $request->get('customer');
  784.         /** @var Customer $customer_ent */
  785.         $customer_ent null;
  786.         $representative $request->get('representative');
  787.         $guid $request->get('guid');
  788.         $header_id $request->get('header_id');
  789.         $getbox $request->get('getbox');
  790.         $getbox $getbox == 'true' true false;
  791.         $data_response = [];
  792.         $entityManager $this->getDoctrine()->getManager();
  793.         /** @var WiCamHeader $wicam_header */
  794.         $wicam_header $entityManager->getRepository(WiCamHeader::class)->find($header_id);
  795.         $no_plz true;
  796.         if ($plz) {
  797.             /** @var PostalCodes $Plz */
  798.             $Plz $entityManager->getRepository(PostalCodes::class)->findBY(['plz' => $plz]);
  799.             if ($Plz) {
  800.                 $no_plz false;
  801.                 $wicam_header->setPlz($plz);
  802.             }
  803.         }
  804.         if (!empty($customer)) {
  805.             /** @var Customer $customer_ent */
  806.             $customer_ent $entityManager->getRepository(Customer::class)->find($customer);
  807.             $wicam_header->setCustomer($customer_ent);
  808.         }
  809.         if (!empty($representative)) {
  810.             /** @var Representative $representative_ent */
  811.             $representative_ent $entityManager->getRepository(Representative::class)->find($representative);
  812.             $wicam_header->setRepresentative($representative_ent);
  813.         }
  814.         $data_files $request->get('data_files');
  815.         if ($data_files) {
  816.             /** @var Setting $setting */
  817.             $setting_specific_weight $entityManager->getRepository(Setting::class)->find(9);
  818.             /** @var Setting $setting_verputzen */
  819.             $setting_verputzen $entityManager->getRepository(Setting::class)->find(13);
  820.             /** @var Setting $setting_general_surcharge */
  821.             $setting_general_surcharge $entityManager->getRepository(Setting::class)->find(11);
  822.             $setting_value json_decode($setting_general_surcharge->getValue(), true);
  823.             $customer =  $wicam_header->getCustomer();
  824.             $surcharge_value 0;
  825.             if(!is_null($customer)){
  826.                 $customer_category $customer->getCategory()->getDescription();
  827.             } else {
  828.                 $customer_category 'no_category';
  829.             }
  830.             foreach($setting_value as $k=>$s){
  831.                 $categoryDescription str_replace('category_','',$k);
  832.                 if($categoryDescription == $customer_category){
  833.                     $surcharge_value $s 1.0;
  834.                 }
  835.             }
  836.             if($surcharge_value == 0){
  837.                 $customer_category 'no_category';
  838.                 foreach($setting_value as $k=>$s){
  839.                     $categoryDescription str_replace('category_','',$k);
  840.                     if($categoryDescription == $customer_category){
  841.                         $surcharge_value $s 1.0;
  842.                     }
  843.                 }
  844.             }
  845.             /** @var Setting $setting_max_drilling */
  846.             $setting_max_drilling $entityManager->getRepository(Setting::class)->find(self::MAX_DRILLING_DIAMETER_ID);
  847.             $surcharges_handlings $entityManager->getRepository(SurchargeHandling::class)->findAll();
  848.             $prices_surcharges_ext $entityManager->getRepository(PriceSurcharge::class)->findAll();
  849.             //create wicamheader temporal object
  850.             $wiCamHeaderTemporal $entityManager->getRepository(WiCamHeaderTemp::class)->findBy(['wicamHeaderId'=>$header_id]);
  851.             foreach ($data_files as $df) {
  852.                 $identify $df['identify'];
  853.                 /** @var WiCamFiles $wicam_file */
  854.                 $wicam_file $entityManager->getRepository(WiCamFiles::class)->find($identify);
  855.                 //fill the JSON object for the wicam_files
  856.                 $wicamFileObject = array(
  857.                     'id'=>$wicam_file->getId(),
  858.                     'wicam_header_id'=>$wicam_file->getWicamHeader()->getId(),
  859.                     'wicam_id'=>$wicam_file->getWicamId(),
  860.                     'collectionID'=>$wicam_file->getCollectionID(),
  861.                     'name'=>$wicam_file->getName(),
  862.                     'originalName'=>$wicam_file->getOriginalName(),
  863.                     'geometryName'=>$wicam_file->getGeometryName(),
  864.                     'extension'=>$wicam_file->getExtension(),
  865.                     'length'=>$wicam_file->getLength(),
  866.                     'width'=>$wicam_file->getWidth(),
  867.                     'partNetArea'=>$wicam_file->getPartNetArea(),
  868.                     'contours'=>$wicam_file->getContours(),
  869.                     'totalLength'=>$wicam_file->getTotalLenght(),
  870.                     'validation'=>$wicam_file->getValidation(),
  871.                     'validation_info'=>$wicam_file->getValidationInfo(),
  872.                     'json'=>$wicam_file->getJson(),
  873.                     'material_grades_id'=>$wicam_file->getMaterialGrades()->getId(),
  874.                     'thickness_id'=>$wicam_file->getThickness()->getId(),
  875.                     'amount'=>$wicam_file->getAmount(),
  876.                     'plz'=>$wicam_file->getPlz(),
  877.                     'total_weight'=>$wicam_file->getTotalWeight(),
  878.                     'total_price'=>$wicam_file->getTotalPrice(),
  879.                     'piece_price'=>$wicam_file->getPiecePrice(),
  880.                     'total_piece_price'=>$wicam_file->getTotalPiecePrice(),
  881.                     'total'=>$wicam_file->getTotal(),
  882.                     'real_weight'=>$wicam_file->getRealWeight(),
  883.                     'delivery_cost'=>$wicam_file->getDeliveryCost(),
  884.                     'png_file'=>$wicam_file->getPngFile(),
  885.                     'svg_file'=>$wicam_file->getSvgFile(),
  886.                     'cutting_time'=>$wicam_file->getCuttingTime(),
  887.                     //'calculation_shape_id'=>$wicam_file->getCalculationShape()->getId(),
  888.                     'is_shape'=>$wicam_file->getIsShape(),
  889.                     'hasCircles'=>$wicam_file->getHasCircles(),
  890.                     'deleted'=>$wicam_file->getDeleted(),
  891.                     'guid'=>$wicam_file->getGuid(),
  892.                     'orden'=>$wicam_file->getOrden(),
  893.                     'creation_date'=>$wicam_file->getCreationDate(),
  894.                 );
  895.                 $wicamFileObj json_encode($wicamFileObject);
  896.                 // var_dump($wicamFileObj);
  897.                 // $wiCamHeaderTemporal->setFileInfo($wicamFileObject);
  898.                 // $old_amount = $wicam_file->getAmount();
  899.                 $thickness_id $df["thickness"];
  900.                 $thickness $entityManager->getRepository(Thickness::class)->findOneBy(["id" => $thickness_id]);
  901.                 $material_grade_id $df["materialgrade"];
  902.                 /** @var MaterialGrades $material_grades */
  903.                 $material_grades $entityManager->getRepository(MaterialGrades::class)->find($material_grade_id);
  904.                 $delivery_cost null;
  905.                 $TotalPrice null;
  906.                 $price_surcharge null;
  907.                 $total_weight null;
  908.                 $piece_price null;
  909.                 $total_piece_price null;
  910.                 $total null;
  911.                 $response = [];
  912.                 $price_surcharge_id $df['price_surcharge'];
  913.                 $amount $df['amount'];
  914.                 /** @var SurchargeDimensions $surcharge_dimension */
  915.                 $surcharge_dimension $entityManager->getRepository(SurchargeDimensions::class)->findOneByThickness($thickness_id);
  916.                 $wicam_file->setMaterialGrades($material_grades);
  917.                 $real_plz substr($plz02);
  918.                 // $orderLimitReached = $this->isValidPricesLimit($header_id);
  919.                 // $newAmountGreaterThanOld = $amount > $old_amount ? true : false;
  920.                 // if ($orderLimitReached) {
  921.                 //     if ($newAmountGreaterThanOld) {
  922.                 //         $amount = $old_amount;
  923.                 //     }
  924.                 // }
  925.                 $amount = empty($amount) ? $amount;
  926.                 if ($amount 0) {
  927.                     $amount 0;
  928.                 }
  929.                 $wicam_file->setThickness($thickness)
  930.                     ->setAmount($amount)
  931.                     ->setPlz($plz);
  932.                 if ($thickness != null && $surcharge_dimension != null && !empty($price_surcharge_id)
  933.                     && !empty($material_grade_id) && $wicam_file->getValidation() == '1') {
  934.                     $total_weight $this->getTotalWeight($wicam_file$thickness$surcharge_dimension$setting_specific_weight);
  935.                     $response['total_weight'] = $total_weight;
  936.                     $ad_handling_percent $this->getAddtionalHandling($surcharges_handlings$total_weight$amount,
  937.                         $wicam_header->getCustomer());
  938.                     $totalMaterialPrices $this->getPriceMaterialAndSurcharges($wicam_file$thickness_id$material_grade_id);
  939.                     $TotalPrice = ($totalMaterialPrices $total_weight) / 1000// get prices by KG
  940.                     $TotalPrice round($TotalPrice2);
  941.                     $response['total_price'] = $TotalPrice;
  942.                     $cutting_time $this->getCuttingTime($wicam_file$setting_max_drilling$thickness_id);
  943.                     $wicam_file->setCuttingTime($cutting_time);
  944.                     /** @var PriceSurcharge $price_surcharge */
  945.                     $price_surcharge $entityManager->getRepository(PriceSurcharge::class)->find($price_surcharge_id);
  946.                     $price_minute $price_surcharge->getPriceMinute() * 1.0;
  947.                     $piece_price $cutting_time $price_minute;
  948.                     $piece_price round($piece_price2);
  949.                     $piece_price += $setting_verputzen->getValue() * 1.0;
  950.                     $piece_price $response['piece_price'] = round($piece_price2);
  951.                     $additional_general_surcharge $surcharge_value 1.0;
  952.                     $additional_general_surcharge = ($additional_general_surcharge 100.0) + 1.0;
  953.                     // Get surcharges EUR PER PIECE
  954.                     if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null){
  955.                         $addtional_per_piece $this->GetSurchargesTotals(self::EUR_PER_PIECEself::IN_PRICE$wicam_file->getId(),
  956.                             $wicam_header->getCustomer()->getCategory()->getId());
  957.                     } else {
  958.                         $addtional_per_piece $this->GetSurchargesTotals(self::EUR_PER_PIECEself::IN_PRICE$wicam_file->getId(),
  959.                             null);
  960.                     }
  961.                     $additional_value_circle $this->getAdditionalValueCircle($header_id);
  962.                     $response['total_piece_price'] = round((($piece_price $TotalPrice $addtional_per_piece $additional_value_circle) * $additional_general_surcharge) * $ad_handling_percent2);
  963.                     if ($amount <= 0) { // if not amount the total piece price must be 0
  964.                         $response['total_piece_price'] = 0.0;
  965.                     }
  966.                     $total_piece_price $response['total_piece_price'];
  967.                     $response['total'] = round(((($piece_price $TotalPrice $addtional_per_piece $additional_value_circle) * $additional_general_surcharge) * $ad_handling_percent) * ($amount 1.0), 2);
  968.                     $response['total_piece_price_str'] = number_format($response['total_piece_price'], 2',''.');
  969.                     if ($request->getLocale() == 'en') {
  970.                         $response['total_piece_price_str'] = $this->currencySymbol ' ' $response['total_piece_price_str'];
  971.                     } else {
  972.                         $response['total_piece_price_str'] = $response['total_piece_price_str'] . ' ' $this->currencySymbol;
  973.                     }
  974.                     // Get surcharges EUR PER FILE
  975.                     if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null) {
  976.                         $addtional_per_file $this->GetSurchargesTotals(self::EUR_EFFECTIVE_PER_FILEself::IN_PRICE$wicam_file->getId(),
  977.                             $wicam_header->getCustomer()->getCategory()->getId());
  978.                     } else {
  979.                         $addtional_per_file $this->GetSurchargesTotals(self::EUR_EFFECTIVE_PER_FILEself::IN_PRICE$wicam_file->getId(),
  980.                             null);
  981.                     }
  982.                     $total $response['total'] = $response['total'] + $addtional_per_file;
  983.                     $response['total_str'] = number_format($response['total'], 2',''.');
  984.                     if ($request->getLocale() == 'en') {
  985.                         $response['total_str'] = $this->currencySymbol ' ' $response['total_str'];
  986.                     } else {
  987.                         $response['total_str'] = $response['total_str'] . ' ' $this->currencySymbol;
  988.                     }
  989.                     $this->deleteWiCamFilesPriceSurcharge($wicam_file);
  990.                     /** @var PriceSurcharge $ps */
  991.                     foreach ($prices_surcharges_ext as $ps) {
  992.                         $price_minute_ext $ps->getPriceMinute();
  993.                         $piece_price_ext $cutting_time $price_minute_ext;
  994.                         $piece_price_ext round($piece_price_ext2);
  995.                         $piece_price_ext += $setting_verputzen->getValue() * 1.0;
  996.                         $total_piece_price_ext round((($piece_price_ext $TotalPrice $addtional_per_piece $additional_value_circle) * $additional_general_surcharge) * $ad_handling_percent2);
  997.                         $total_ext round(((($piece_price_ext $TotalPrice $addtional_per_piece $additional_value_circle) * $additional_general_surcharge) * $ad_handling_percent) * ($amount 1.0), 2);
  998.                         $total_ext $total_ext $addtional_per_file;
  999.                         /** @var WiCamFilesPriceSurcharge $WiCamFilesPriceSurcharge */
  1000.                         $WiCamFilesPriceSurcharge = new WiCamFilesPriceSurcharge();
  1001.                         $WiCamFilesPriceSurcharge->setWicamFiles($wicam_file)
  1002.                             ->setPriceSurcharge($ps)
  1003.                             ->setPiecePrice($piece_price_ext)
  1004.                             ->setTotalPiecePrice($total_piece_price_ext)
  1005.                             ->setTotal($total_ext);
  1006.                         $entityManager->persist($WiCamFilesPriceSurcharge);
  1007.                     }
  1008.                     $real_weight round($wicam_file->getRealWeight(), 2);
  1009.                     $response['real_weight'] = $real_weight;
  1010.                     $tooltip $this->renderView('includes/tooltip-content.html.twig', [
  1011.                         'total_weight'      => round($response['total_weight'], 2),
  1012.                         'piece_price'       => $response['piece_price'],
  1013.                         'real_weight'       => round($response['real_weight'], 2),
  1014.                         'total_piece_price' => $response['total_piece_price'],
  1015.                         'total_price'       => $response['total_price']
  1016.                     ]);
  1017.                 } else {
  1018.                     $response['total_weight'] = 0.0;
  1019.                     $response['total'] = 0.0;
  1020.                     $response['total_str'] = number_format(0.02',''.');
  1021.                     if ($request->getLocale() == 'en') {
  1022.                         $response['total_str'] = $this->currencySymbol ' ' $response['total_str'];
  1023.                     } else {
  1024.                         $response['total_str'] = $response['total_str'] . ' ' $this->currencySymbol;
  1025.                     }
  1026.                     $real_weight round($wicam_file->getRealWeight(), 2);
  1027.                     $tooltip $this->renderView('includes/tooltip-content.html.twig',
  1028.                         [
  1029.                             'real_weight' => $real_weight
  1030.                         ]
  1031.                     );
  1032.                 }
  1033.                 $wicam_file->setTotalWeight($total_weight)
  1034.                     ->setTotalPrice($TotalPrice)
  1035.                     ->setPiecePrice($piece_price)
  1036.                     ->setTotalPiecePrice($total_piece_price)
  1037.                     ->setTotal($total)
  1038.                     ->setDeliveryCost($delivery_cost)
  1039.                     ->setMaterialGrades($material_grades)
  1040.                     ->setPriceSurcharge($price_surcharge);
  1041.                 $wicam_file->setFreightPricesCargo(null);
  1042.                 $wicam_file->setFreightPricesTruck(null);
  1043.                 // Get surcharges EUR PER PIECE SEPARATE VALUE
  1044.                 if(!is_null($customer)){
  1045.                 $this->GetSurchargesTotals(self::EUR_PER_PIECEself::SEPARATED_PRICE$wicam_file->getId(),
  1046.                     $customer->getCategory()->getId());
  1047.                 $this->GetSurchargesTotals(self::EUR_EFFECTIVE_PER_FILEself::SEPARATED_PRICE$wicam_file->getId(),
  1048.                     $customer->getCategory()->getId());
  1049.                 } else {
  1050.                     $this->GetSurchargesTotals(self::EUR_PER_PIECEself::SEPARATED_PRICE$wicam_file->getId(),
  1051.                         null);
  1052.                     $this->GetSurchargesTotals(self::EUR_EFFECTIVE_PER_FILEself::SEPARATED_PRICE$wicam_file->getId(),
  1053.                         null);
  1054.                 }
  1055.                 $response['tooltip'] = $tooltip;
  1056.                 $data_response[$identify] = $response;
  1057.                 $entityManager->flush();
  1058.             }
  1059.         }
  1060.         // $new response
  1061.         $response = [];
  1062.         $response['data_files'] = $data_response;
  1063.         if ($getbox) {
  1064.             $response_delivery $this->GetDeliveryType($guid$header_id$real_plz);
  1065.             if ($response_delivery['transport'] == 3) {
  1066.                 $wicam_header->setDeliveryCost($response_delivery['delivery_cost']);
  1067.                 $wicam_header->setDeliveryType($response_delivery['transport']);
  1068.                 $no_plz false;
  1069.             } else if (isset($real_plz)) {
  1070.                 $no_plz true;
  1071.                 $response_delivery $this->GetDeliveryType($guid$header_id$real_plz);
  1072.                 $wicam_header->setDeliveryCost($response_delivery['delivery_cost']);
  1073.                 $wicam_header->setDeliveryType($response_delivery['transport']);
  1074.             } else {
  1075.                 $wicam_header->setDeliveryCost(null);
  1076.                 $wicam_header->setDeliveryType("");
  1077.             }
  1078.             $entityManager->flush();
  1079.             if(!is_null($customer)){
  1080.                 $buybox $this->GetBuyBox($guid$header_idfalse$customer->getCategory()->getId());
  1081.             } else {
  1082.                 $buybox $this->GetBuyBox($guid$header_idfalsenull);
  1083.             }
  1084.             $response['buybox'] = $buybox;
  1085.             $response['no_plz'] = $no_plz;
  1086.             $response['transport'] = $response_delivery['transport'];
  1087.         }
  1088.         return new JsonResponse($response);
  1089.     }
  1090.     private function GetSurchargesTotals(int $price_formint $type_additionint $wicam_file_id$category_id)
  1091.     {
  1092.         /** @var EntityRepository $repository */
  1093.         $repository $this->getDoctrine()->getRepository(WiCamFilesSurcharges::class);
  1094.         $qb $repository->createQueryBuilder('ws');
  1095.         if ($type_addition == self::IN_PRICE) {
  1096.             $qb $qb
  1097.                 ->select('SUM(sc.price) AS TotalPrice')
  1098.                 ->leftJoin('ws.surcharges''s')
  1099.                 ->leftJoin('ws.surcharges_category''sc')
  1100.                 ->where('ws.wicam_files = :wicam_files')
  1101.                 ->andWhere('s.price_form = :price_form')
  1102.                 ->andWhere('s.type_addition = :type_addition')
  1103.                 ->andWhere('s.active = :active')
  1104.                 ->andwhere('sc.category = :category')
  1105.                 ->setParameter('wicam_files'$wicam_file_id)
  1106.                 ->setParameter('price_form'$price_form)
  1107.                 ->setParameter('type_addition'$type_addition)
  1108.                 ->setParameter('active'1)
  1109.                 ->setParameter('category'$category_id)
  1110.                 ->getQuery();
  1111.             $total $qb->getOneOrNullResult();
  1112.         } else {
  1113.             $qb $qb
  1114.                 ->select('ws.id,sc.price')
  1115.                 ->leftJoin('ws.surcharges''s')
  1116.                 ->leftJoin('ws.surcharges_category''sc')
  1117.                 ->where('ws.wicam_files = :wicam_files')
  1118.                 ->andWhere('s.price_form = :price_form')
  1119.                 ->andWhere('s.type_addition = :type_addition')
  1120.                 ->andWhere('s.active = :active')
  1121.                 ->andWhere('sc.category = :category')
  1122.                 ->setParameter('wicam_files'$wicam_file_id)
  1123.                 ->setParameter('price_form'$price_form)
  1124.                 ->setParameter('type_addition'$type_addition)
  1125.                 ->setParameter('active'1)
  1126.                 ->setParameter('category'$category_id)
  1127.                 ->getQuery()
  1128.                 ->getResult();
  1129.             $entityManager $this->getDoctrine()->getManager();
  1130.             /** @var WiCamFilesSurcharges $ws */
  1131.             /** @var WiCamFiles $wicam_file $sh */
  1132.             $wicam_file $entityManager->getRepository(WiCamFiles::class)->find($wicam_file_id);
  1133.             if (!empty($qb)) {
  1134.                 foreach ($qb as $sh) {
  1135.                     $ws $entityManager->getRepository(WiCamFilesSurcharges::class)->find($sh['id']);
  1136.                     if ($price_form == self::EUR_PER_PIECE) {
  1137.                         $ws->setSeparateValue($sh['price'] * $wicam_file->getAmount());
  1138.                     } elseif ($price_form == self::EUR_EFFECTIVE_PER_FILE || $price_form == self::EUR_EFFECTIVE_FOR_ORDER) {
  1139.                         $ws->setSeparateValue($sh['price']);
  1140.                     }
  1141.                     $entityManager->flush();
  1142.                 }
  1143.             }
  1144.             $total['TotalPrice'] = 0;
  1145.         }
  1146.         return (empty($total['TotalPrice']) ? 0.0 $total['TotalPrice']);
  1147.     }
  1148.     /**
  1149.      * @Route("/upload/calculate-weight",  methods={"POST"}, name="wi_cam_calculate_weight")
  1150.      * @param Request $request
  1151.      *
  1152.      * @return JsonResponse
  1153.      */
  1154.     public function CalculateRealWeight(Request $request): JsonResponse
  1155.     {
  1156.         /**
  1157.          * @var Thickness   $thickness
  1158.          * @var Setting     $setting
  1159.          * @var WiCamFiles  $wicam_file
  1160.          * @var WiCamHeader $wicam_header
  1161.          */
  1162.         $guid $request->get('guid');
  1163.         $header_id $request->get('header_id');
  1164.         $data_files $request->get('data_files');
  1165.         $entityManager $this->getDoctrine()->getManager();
  1166.         if ($data_files) {
  1167.             foreach ($data_files as $df) {
  1168.                 $thickness_id $df["thickness"];
  1169.                 $identify $df['identify'];
  1170.                 $wicam_file $entityManager->getRepository(WiCamFiles::class)->find($identify);
  1171.                 if (!empty($thickness_id)) {
  1172.                     $thickness $entityManager->getRepository(Thickness::class)->findOneBy(["id" => $thickness_id]);
  1173.                     $setting $entityManager->getRepository(Setting::class)->find(9);
  1174.                     $partNetArea $wicam_file->getPartNetArea();
  1175.                     $thickness_vl $thickness->getValue() * 1.0;
  1176.                     $specific_weight $setting->getValue() * 1.0;
  1177.                     $real_weight = (($partNetArea 1.0) * $thickness_vl $specific_weight) / 1000000;
  1178.                     $wicam_file->setRealWeight($real_weight);
  1179.                     $wicam_file->setThickness($thickness);
  1180.                 } else {
  1181.                     $wicam_file->setRealWeight(null);
  1182.                     $wicam_file->setThickness(null);
  1183.                 }
  1184.                 //var_dump($real_weight); die;
  1185.                 $entityManager->flush();
  1186.             }
  1187.         }
  1188.         return $this->Calculate($request);
  1189.     }
  1190.     private function getFpp($length,$width,$real_weight,$thickness){
  1191.         $freightPricesPackage $this->entityManager->getRepository(FreightPricesPackage::class)->isLike(
  1192.             ['length' => $length'width' => $width'weight' => $real_weight'height' => $thickness]);
  1193.         if (!empty($freightPricesPackage)) {
  1194.             $result_length = [];
  1195.             $result_width = [];
  1196.             $result_height = [];
  1197.             $result_weight = [];
  1198.             foreach ($freightPricesPackage as $fpp) {
  1199.                 $result_length[] = $fpp->getLength();
  1200.                 $result_width[] = $fpp->getWidth();
  1201.                 $result_height[] = $fpp->getHeight();
  1202.                 $result_weight[] = $fpp->getWeight();
  1203.             }
  1204.             $min_length min($result_length);
  1205.             $min_width min($result_width);
  1206.             $min_height min($result_height);
  1207.             $min_weight min($result_weight);
  1208.             return $fppMin $this->entityManager->getRepository(FreightPricesPackage::class)->findBY(
  1209.                 ['length' => $min_length'width' => $min_width'height' => $min_height'weight' => $min_weight],
  1210.                 ['price' => 'ASC']
  1211.             );
  1212.         }
  1213.     }
  1214.     private function getParcelAmount($amount_left,$pieces_per_parcel,$parcel_amount){
  1215.         $amount_left $amount_left $pieces_per_parcel;
  1216.         if ($amount_left == 0) {
  1217.             $parcel_amount++;
  1218.         } else {
  1219.             while ($amount_left != 0) {
  1220.                 $parcel_amount++;
  1221.                 if ($amount_left 0) {
  1222.                     $amount_left 0;
  1223.                 } else {
  1224.                     $amount_left $amount_left $pieces_per_parcel;
  1225.                     if($amount_left == 0){
  1226.                         $parcel_amount++;
  1227.                     }
  1228.                 }
  1229.             }
  1230.         }
  1231.         return $parcel_amount;
  1232.     }
  1233.     function isParcelFull($total_pieces$pieces_per_parcel) {
  1234.         $parcels ceil($total_pieces $pieces_per_parcel);
  1235.         $result = [];
  1236.         for ($i 1$i <= $parcels$i++) {
  1237.             $remaining_pieces $total_pieces - ($i 1) * $pieces_per_parcel;
  1238.             $is_full = ($remaining_pieces >= $pieces_per_parcel) ? true false;
  1239.             $result[] = $is_full;
  1240.         }
  1241.         return $result;
  1242.     }
  1243.     /**
  1244.      * @param $guid
  1245.      * @param $header_id
  1246.      * @param $real_plz
  1247.      *
  1248.      * @return array
  1249.      */
  1250.     private function GetDeliveryType($guid$header_id$real_plz): array
  1251.     {
  1252.         $entityManager $this->getDoctrine()->getManager();
  1253.         /** @var Setting $max_weight_pal */
  1254.         $max_weight_pal $entityManager->getRepository(Setting::class)->find(self::MAX_WEIGHT_PALLET);
  1255.         /** @var Setting $max_length_pal */
  1256.         $max_length_pal $entityManager->getRepository(Setting::class)->find(self::MAX_LENGTH_PALLET);
  1257.         /** @var Setting $max_width_pal */
  1258.         $max_width_pal $entityManager->getRepository(Setting::class)->find(self::MAX_WIDTH_PALLET);
  1259.         $files $entityManager->getRepository(WiCamFiles::class)->findBy(['wicam_header' => $header_id'deleted' => 0'validation' => '1']);
  1260.         $c_cargo 0;
  1261.         $c_truck 0;
  1262.         $c_package 0;
  1263.         $sum_real_weight 0.0;
  1264.         $delivery_costPackage 0.0;
  1265.         $transport 0;
  1266.         $delivery_cost 0.0;
  1267.         $dts = new DeliveryTypeService($this->entityManager);
  1268.         $parcelInfo $dts->run($files);
  1269.         // var_dump($parcelInfo);
  1270.         // die;
  1271.         if(!$parcelInfo['isParcel']){
  1272.             /** @var WiCamFiles $item */
  1273.             foreach ($files as $item) {
  1274.                 $width $item->getWidth();
  1275.                 $length $item->getLength();
  1276.                 $real_weight $item->getRealWeight() * $item->getAmount();
  1277.                 $thickness $item->getThickness()->getValue();
  1278.                 if (
  1279.                     $width <= (float)$max_width_pal->getValue()
  1280.                     && $length <= (float)$max_length_pal->getValue()
  1281.                     && $real_weight <= (float)$max_weight_pal->getValue()
  1282.                 ) {
  1283.                     $c_cargo++;
  1284.                 } else {
  1285.                     $c_truck++;
  1286.                 }
  1287.                 $sum_real_weight += $real_weight;
  1288.             }
  1289.             $delivery_costCargo 0.0;
  1290.             $delivery_costTruck 0.0;
  1291.             if (!empty($real_plz)) {
  1292.                 /********** Calculation for Cargo **********/
  1293.                 $freightpricescargo $entityManager->getRepository(FreightPricesCargo::class)->findOneBy(['postal_code' => $real_plz]);
  1294.                 if (!is_null($freightpricescargo)) {
  1295.                     if ($sum_real_weight 150) {
  1296.                         $delivery_costCargo $freightpricescargo->getRange1();
  1297.                     } else if (150 <= $sum_real_weight && $sum_real_weight 300) {
  1298.                         $delivery_costCargo $freightpricescargo->getRange2();
  1299.                     } else if (300 <= $sum_real_weight && $sum_real_weight 500) {
  1300.                         $delivery_costCargo $freightpricescargo->getRange3();
  1301.                     } else if (500 <= $sum_real_weight && $sum_real_weight 800) {
  1302.                         $delivery_costCargo $freightpricescargo->getRange4();
  1303.                     } else if (800 <= $sum_real_weight && $sum_real_weight 1000) {
  1304.                         $delivery_costCargo $freightpricescargo->getRange5();
  1305.                     }
  1306.                 }
  1307.                 /********** Calculation for Truck **********/
  1308.                 /** @var FreightPricesTruck $freightpricestruck */
  1309.                 $freightpricestruck $entityManager->getRepository(FreightPricesTruck::class)->findOneBy(['postal_code' => $real_plz]);
  1310.                 if (!is_null($freightpricestruck)) {
  1311.                     $tonnes $sum_real_weight 1000;
  1312.                     while ($tonnes 0.0) {
  1313.                         if ($tonnes >= 24.0) {
  1314.                             $delivery_costTruck += $freightpricestruck->getUpTwentyFour() * 1.0;
  1315.                             $tonnes $tonnes 24.0;
  1316.                         } elseif ($tonnes >= 12.0) {
  1317.                             $delivery_costTruck += $freightpricestruck->getUpTwelve() * 1.0;
  1318.                             $tonnes $tonnes 12.0;
  1319.                         } else {
  1320.                             $delivery_costTruck += $freightpricestruck->getUpFive() * 1.0;
  1321.                             $tonnes 0.0;
  1322.                         }
  1323.                     }
  1324.                 }
  1325.             }
  1326.             // 1 = truck
  1327.             // 2 == pallet
  1328.             // 3 == package
  1329.             if ($c_truck 0) {
  1330.                 $transport 1;
  1331.                 $delivery_cost $delivery_costTruck;
  1332.             } else if ($c_cargo 0) {
  1333.                 if ($delivery_costCargo == 0) { // if cargo is empty then we need to send to truck
  1334.                     $delivery_cost $delivery_costTruck;
  1335.                     $transport 1;
  1336.                 } else {
  1337.                     if ($delivery_costCargo <= $delivery_costTruck) {
  1338.                         $delivery_cost $delivery_costCargo;
  1339.                         $transport 2;
  1340.                     } else {
  1341.                         $delivery_cost $delivery_costTruck;
  1342.                         $transport 1;
  1343.                     }
  1344.                 }
  1345.             }
  1346.         } else {
  1347.             $transport 3;
  1348.             $delivery_cost $parcelInfo['totalDeliveryCost'];
  1349.         }
  1350.         $response['transport'] = $transport;
  1351.         $response['sum_real_weight'] = $sum_real_weight;
  1352.         $response['delivery_cost'] = $delivery_cost;
  1353.         return $response;
  1354.     }
  1355.     public function GetBuyBox($guid$header_id$return_data false$category_id)
  1356.     {
  1357.         $entityManager $this->getDoctrine()->getManager();
  1358.         /** @var WiCamHeader $wiCamHeader */
  1359.         $wiCamHeader $entityManager->getRepository(WiCamHeader::class)->find($header_id);
  1360.         /** @var Setting $setting_min_price */
  1361.         $setting_min_price $entityManager->getRepository(Setting::class)->find(12);
  1362.         $setting_value json_decode($setting_min_price->getValue(), true);
  1363.         $customer =  $wiCamHeader->getCustomer();
  1364.         $minimum_value 0;
  1365.         if(!is_null($customer)){
  1366.             $customer_category $customer->getCategory()->getDescription();
  1367.         } else {
  1368.             $customer_category 'no_category';
  1369.         }
  1370.         foreach($setting_value as $k=>$s){
  1371.             $categoryDescription str_replace('category_','',$k);
  1372.             if($categoryDescription == $customer_category){
  1373.                 $minimum_value $s 1.0;
  1374.             }
  1375.         }
  1376.         if($minimum_value == 0){
  1377.             $customer_category 'no_category';
  1378.             foreach($setting_value as $k=>$s){
  1379.                 $categoryDescription str_replace('category_','',$k);
  1380.                 if($categoryDescription == $customer_category){
  1381.                     $minimum_value $s 1.0;
  1382.                 }
  1383.             }
  1384.         }
  1385.         /** @var Setting $setting_mvat_percent */
  1386.         $setting_mvat_percent $entityManager->getRepository(Setting::class)->find(static::VAT_PERCENT);
  1387.         /** @var EntityRepository $repository */
  1388.         $repository $entityManager->getRepository(WiCamFiles::class);
  1389.         $qb $repository->createQueryBuilder('w');
  1390.         $result $qb->select("  SUM(w.total) as total ")
  1391.             ->where(' w.guid = :guid ')
  1392.             ->andWhere(' w.deleted = 0 ')
  1393.             ->andWhere(' w.validation = :val_validation ')
  1394.             ->andWhere(' w.wicam_header = :wicam_header ')
  1395.             ->setParameter('guid'$guid)
  1396.             ->setParameter('wicam_header'$header_id)
  1397.             ->setParameter('val_validation''1')
  1398.             ->getQuery()
  1399.             ->getOneOrNullResult();
  1400.         /** @var WiCamHeader $wiCamHeader */
  1401.         $wiCamHeader $entityManager->getRepository(WiCamHeader::class)->find($header_id);
  1402.         $old_totales $wiCamHeader->getGeneralTotal();
  1403.         // SURCHARGES
  1404.         /** @var EntityRepository $repository */
  1405.         $repository $this->getDoctrine()->getRepository(WiCamFilesSurcharges::class);
  1406.         $qb $repository->createQueryBuilder('ws');
  1407.         $qb $qb
  1408.             ->select('s.id,s.description,SUM(sc.price) AS total')
  1409.             ->innerJoin('ws.surcharges''s')
  1410.             ->innerJoin('ws.wicam_files''wf')
  1411.             ->innerJoin('ws.surcharges_category''sc')
  1412.             ->where('wf.wicam_header = :wicam_header')
  1413.             ->andWhere('s.type_addition = :type_addition')
  1414.             ->andWhere('s.active = :active')
  1415.             ->andWhere('wf.deleted = :deleted')
  1416.             ->andWhere('sc.category = :category')
  1417.             ->groupBy('s.id')
  1418.             ->addGroupBy('s.description')
  1419.             ->setParameter('wicam_header'$header_id)
  1420.             ->setParameter('type_addition'self::SEPARATED_PRICE)
  1421.             ->setParameter('active'1)
  1422.             ->setParameter('deleted'0)
  1423.             ->setParameter('category'$category_id)
  1424.             ->getQuery()
  1425.             ->getResult();
  1426.         $surcharges_total 0.0;
  1427.         if (!empty($qb)) {
  1428.             foreach ($qb as $key => $sr) {
  1429.                 $surcharge $entityManager->getRepository(Surcharges::class)->find($sr['id']);
  1430.                 $qb[$key]['surcharge'] = $surcharge;
  1431.                 $surcharges_total += empty($sr['total']) ? 0.0 $sr['total'];
  1432.             }
  1433.         }
  1434.         $deliveryCost = !empty($wiCamHeader->getDeliveryCost()) ? $wiCamHeader->getDeliveryCost() : 0.0;
  1435.         $vatPercent $setting_mvat_percent->getValue();
  1436.         $subTotal $result['total'] + $surcharges_total $deliveryCost;
  1437.         if ($subTotal <= $minimum_value) {
  1438.             $minimun_vl $minimum_value $subTotal;
  1439.             $subTotal $minimum_value;
  1440.         }
  1441.         $vatPercentTotal $subTotal * ($vatPercent 100);
  1442.         $totales $subTotal $vatPercentTotal;
  1443.         $wiCamHeader->setGeneralTotalPrice($result['total']);
  1444.         $wiCamHeader->setSurchargesTotal($surcharges_total);
  1445.         $wiCamHeader->setVatPercent($vatPercent);
  1446.         $wiCamHeader->setVatPercentTotal($vatPercentTotal);
  1447.         $wiCamHeader->setGeneralTotal($totales);
  1448.         $entityManager->flush();
  1449.         $orderReachedLimit $this->isValidPricesLimit($header_id);
  1450.         $newTotalGreaterThanOld $totales $old_totales true false;
  1451.         // var_dump($newTotalGreaterThanOld, 'totales: '.$totales.' old totales: '.$old_totales);
  1452.         $show_validation_message "";
  1453.         if ($newTotalGreaterThanOld && $orderReachedLimit) {
  1454.             $totales $old_totales;
  1455.             $wicamHeaderTemporal $this->getDoctrine()->getRepository(WiCamHeaderTemp::class)->findOneBy(['wicamHeaderId' => $header_id]);
  1456.             if(!empty($wicamHeaderTemporal)){
  1457.                 $wiCamHeader->setGeneralTotalPrice($wicamHeaderTemporal->getGeneralTotalPrice());
  1458.                 $wiCamHeader->setSurchargesTotal($wicamHeaderTemporal->getSurchargesTotal());
  1459.                 $wiCamHeader->setVatPercent($wicamHeaderTemporal->getVatPercent());
  1460.                 $wiCamHeader->setVatPercentTotal($wicamHeaderTemporal->getVatPercentTotal());
  1461.                 $wiCamHeader->setGeneralTotal($wicamHeaderTemporal->getGeneralTotal());
  1462.                 $entityManager->flush();
  1463.                 $entityManager->remove($wicamHeaderTemporal);
  1464.                 $entityManager->persist($wicamHeaderTemporal);
  1465.             }
  1466.             $show_validation_message "YOU have reached your total purchase limit";
  1467.         }
  1468.         $dataCalculator = [
  1469.             'total'           => $result['total'],
  1470.             'vatPercent'      => $vatPercent,
  1471.             'wicamheader'     => $wiCamHeader,
  1472.             'surcharges'      => $qb,
  1473.             'minimun'         => $minimum_value,
  1474.             'vatPercentTotal' => $vatPercentTotal,
  1475.             'generalTotal'    => $totales,
  1476.             'surchargesTotal' => $surcharges_total,
  1477.             'newTotal'        => $newTotalGreaterThanOld,
  1478.             'purchaseLimit'   => $orderReachedLimit,
  1479.             'val_message'     => $show_validation_message,
  1480.         ];
  1481.         if ($return_data) {
  1482.             return $dataCalculator;
  1483.         }
  1484.         $buybox $this->renderView('includes/buybox-wicam.html.twig'$dataCalculator);
  1485.         $buybox_m $this->renderView('includes/buybox-wicam-mobile-overview.html.twig'$dataCalculator);
  1486.         $response['buyboxdp'] = $buybox;
  1487.         $response['buyboxmb'] = $buybox_m;
  1488.         return $response;
  1489.     }
  1490.     /**
  1491.      * @Route("/upload/total",  methods={"GET"}, name="wi_cam_total")
  1492.      * @param Request $request
  1493.      *
  1494.      * @return JsonResponse
  1495.      */
  1496.     public function Total(Request $request)
  1497.     {
  1498.         $entityManager $this->getDoctrine()->getManager();
  1499.         $guid $request->get('guid');
  1500.         $header_id $request->get('header_id');
  1501.         $wicam_header $entityManager->getRepository(WiCamHeader::class)->find($header_id);
  1502.         if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null){
  1503.             $category_id $wicam_header->getCustomer()->getCategory()->getId();
  1504.         } else {
  1505.             $category_id null;
  1506.         }
  1507.         $buybox $this->GetBuyBox($guid$header_idfalse$category_id);
  1508.         $response['buybox'] = $buybox;
  1509.         return new JsonResponse($response);
  1510.     }
  1511.     /**
  1512.      * @Route("/upload/delete",  methods={"POST"}, name="wi_cam_delete")
  1513.      * @param Request $request
  1514.      *
  1515.      * @return JsonResponse
  1516.      */
  1517.     public function deleteItem(Request $request)
  1518.     {
  1519.         $identify $request->get('identify');
  1520.         /**
  1521.          * @var WiCamFiles $file
  1522.          */
  1523.         $entityManager $this->getDoctrine()->getManager();
  1524.         $file $entityManager->getRepository(WiCamFiles::class)->find($identify);
  1525.         $file->setDeleted(true);
  1526.         $entityManager->flush();
  1527.         $response['status'] = true;
  1528.         return new JsonResponse($response);
  1529.     }
  1530.     /**
  1531.      * @Route("/upload/zipcodes",  methods={"GET"}, name="wi_cam_postcodes")
  1532.      * @param Request $request
  1533.      *
  1534.      * @return JsonResponse
  1535.      */
  1536.     public function GetPostCodes(Request $request)
  1537.     {
  1538.         /**
  1539.          * @var PostalCodes $postalcodes
  1540.          */
  1541.         $term $request->get("term");
  1542.         $entityManager $this->getDoctrine()->getManager();
  1543.         $postalcodes $entityManager->getRepository(PostalCodes::class)->findByPlzField($term);
  1544.         $response = [];
  1545.         $i 0;
  1546.         foreach ($postalcodes as $pt) {
  1547.             $response[$i]['value'] = $pt->getPlz();
  1548.             $response[$i]['label'] = $pt->getPlz() . " - " $pt->getOrt() . " - " $pt->getBundesland();
  1549.             $response[$i]['city'] = $pt->getOrt() . " - " $pt->getBundesland();
  1550.             $i++;
  1551.         }
  1552.         return new JsonResponse($response);
  1553.     }
  1554.     public function getImage($token$id$collectionId)
  1555.     {
  1556.         $response $this->api_client->DownloadFile($token$id$collectionId);
  1557.         //sleep(1);
  1558.         //$fileInformation = $this->GetInformationFile($token,$id);
  1559.         $finalResponse = [
  1560.             'image'  => $response['content'],
  1561.             'status' => $response['status']
  1562.         ];
  1563.         return $finalResponse;
  1564.     }
  1565.     public function getImagePng($token$id$collectionId)
  1566.     {
  1567.         $response $this->api_client->DownloadFilePng($token$id$collectionId);
  1568.         //sleep(1);
  1569.         //$fileInformation = $this->GetInformationFile($token,$id);
  1570.         $finalResponse = [
  1571.             'image'  => $response['content'],
  1572.             'status' => $response['status']
  1573.         ];
  1574.         return $finalResponse;
  1575.     }
  1576.     private function GetToken(Request $request)
  1577.     {
  1578.         /*$token_response = $this->tokenClient->getToken();
  1579.         $request->getSession()->set("wicam_token",$token_response['access_token']);
  1580.         $token_send = $token_response['access_token'];*/
  1581.         $session $request->getSession();
  1582.         $token_send $session->get('wicam_token');
  1583.         $token_time $session->get('wicam_token_time');
  1584.         $now date('Y-m-d H:i:s');
  1585.         if (!empty($token_time)) {
  1586.             $start_ts strtotime($token_time);
  1587.             $end_ts strtotime($now);
  1588.             $diff $end_ts $start_ts;
  1589.             $diffFinal round($diff 60);
  1590.             if ($diffFinal 55) {
  1591.                 $token_send '';
  1592.             }
  1593.         } else {
  1594.             $token_send '';
  1595.         }
  1596.         if (empty($token_send)) {
  1597.             $token_response $this->tokenClient->getToken();
  1598.             $request->getSession()->set("wicam_token"$token_response['access_token']);
  1599.             $request->getSession()->set("wicam_token_time"$now);
  1600.             $token_send $token_response['access_token'];
  1601.         }
  1602.         return $token_send;
  1603.     }
  1604.     /**
  1605.      * @param $wicam_header_id
  1606.      *
  1607.      * @return mixed
  1608.      * @throws \Doctrine\ORM\NonUniqueResultException
  1609.      */
  1610.     public function getCuttingTimeByWicamHeader($wicam_header_id)
  1611.     {
  1612.         $repository_cutting $this->getDoctrine()->getRepository(WiCamFiles::class);
  1613.         $qb_cutting $repository_cutting->createQueryBuilder('qc');
  1614.         $qb_cutting $qb_cutting
  1615.             ->select('COALESCE(SUM(qc.cutting_time*qc.amount),0.0) AS cutting_time')
  1616.             ->where('qc.wicam_header = :wicam_header')
  1617.             ->andWhere('qc.deleted = :deleted')
  1618.             ->setParameter('wicam_header'$wicam_header_id)
  1619.             ->setParameter('deleted'0)
  1620.             ->getQuery()
  1621.             ->setMaxResults(1)
  1622.             ->getOneOrNullResult();
  1623.         return $qb_cutting['cutting_time'];
  1624.     }
  1625.     /**
  1626.      * @Route("/upload/calendar_settings/{id}",  methods={"GET"}, name="wi_cam_calendar_days")
  1627.      * @param Request $request
  1628.      *
  1629.      * @return JsonResponse
  1630.      */
  1631.     public function getDeliveryDays(Request $request): JsonResponse
  1632.     {
  1633.         $date_initial = new \DateTime("NOW");
  1634.         /** @var PriceSurcharge $priceSurcharge
  1635.          * @var PriceSurcharge $priceSurchargeNext
  1636.          * @var Setting        $setting
  1637.          */
  1638.         $wicam_header_id $request->get("id");
  1639.         /** @var WiCamHeader $wicam_header */
  1640.         $wicam_header $this->getDoctrine()->getRepository(WiCamHeader::class)->find($wicam_header_id);
  1641.         if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null) {
  1642.             $category_id $wicam_header->getCustomer()->getCategory()->getId();
  1643.         } else {
  1644.             $category_id null;
  1645.         }
  1646.         // Get Max Additional days
  1647.         /** @var EntityRepository $repository */
  1648.         $repository $this->getDoctrine()->getRepository(WiCamFilesSurcharges::class);
  1649.         $qb $repository->createQueryBuilder('ws');
  1650.         $qb $qb
  1651.             ->select('MAX(s.addition_days) as addition_days')
  1652.             ->leftJoin('ws.surcharges''s')
  1653.             ->leftJoin('ws.wicam_files''wf')
  1654.             ->where('wf.wicam_header = :wicam_header')
  1655.             ->andWhere('s.active = :active')
  1656.             ->andWhere('wf.deleted = :deleted')
  1657.             ->setParameter('wicam_header'$wicam_header_id)
  1658.             ->setParameter('active'1)
  1659.             ->setParameter('deleted'0)
  1660.             ->getQuery()
  1661.             ->getResult();
  1662.         $repository $this->getDoctrine()->getRepository(WiCamFilesSurcharges::class);
  1663.         $qbTotals $repository->createQueryBuilder('ws');
  1664.         $qbTotals $qbTotals
  1665.             ->select('COALESCE(SUM(sc.price),0.0) AS total')
  1666.             ->leftJoin('ws.surcharges''s')
  1667.             ->leftJoin('ws.wicam_files''wf')
  1668.             ->leftJoin('ws.surcharges_category''sc')
  1669.             ->where('wf.wicam_header = :wicam_header')
  1670.             ->andWhere('s.type_addition = :type_addition')
  1671.             ->andWhere('s.active = :active')
  1672.             ->andWhere('wf.deleted = :deleted')
  1673.             ->andWhere('sc.category = :category')
  1674.             ->setParameter('wicam_header'$wicam_header_id)
  1675.             ->setParameter('type_addition'self::SEPARATED_PRICE)
  1676.             ->setParameter('active'1)
  1677.             ->setParameter('deleted'0)
  1678.             ->setParameter('category'$category_id)
  1679.             ->getQuery()
  1680.             ->setMaxResults(1)
  1681.             ->getOneOrNullResult();
  1682.         $addition_days $qb[0]['addition_days'];
  1683.         $labels = [];
  1684.         $colors = [];
  1685.         $legends_colors = [];
  1686.         $sum_cutting_time $this->getCuttingTimeByWicamHeader($wicam_header_id);
  1687.         $priceSurcharge $this->getDoctrine()->getRepository(PriceSurcharge::class)->findOneByDaysNextException(0$sum_cutting_time);
  1688.         $setting $this->getDoctrine()->getRepository(Setting::class)->find(10);
  1689.         $max_available_days $setting->getValue();
  1690.         $is_first_date true;
  1691.         $min '';
  1692.         while (!empty($priceSurcharge)) {
  1693.             $date_initial = new \DateTime("NOW");
  1694.             $priceSurchargeNext $this->getDoctrine()->getRepository(PriceSurcharge::class)->findOneByDaysNextException($priceSurcharge->getId(), $sum_cutting_time);
  1695.             //$date_initial->add(new \DateInterval('P'.$priceSurcharge->getDays().'D'));
  1696.             $days_increment 0;
  1697.             if (!$is_first_date) {
  1698.                 $days_increment 1;
  1699.             }
  1700.             for ($i 1$i <= ($priceSurcharge->getDays() + $days_increment); $i++) {
  1701.                 $date_initial $this->AddDateExcludeWeekends($date_initial1);
  1702.             }
  1703.             if ($is_first_date) {
  1704.                 $min $date_initial->format('Y-m-d');
  1705.             }
  1706.             $is_first_date false;
  1707.             //echo "\n".($priceSurcharge->getDays()+1)."\n\n";
  1708.             $date_f $date_initial->format('Y-m-d');
  1709.             $date_fi str_replace("-"""$date_f);
  1710.             //echo $date_f."\n";
  1711.             $labels["$date_f"] = ['start' => $date_f'price_surcharge' => $priceSurcharge->getId()];
  1712.             //$labels[$date_f] = array('start'=>$date_f,'title'=>'$ '.$priceSurcharge->getPriceMinute(),'price_surcharge'=>$priceSurcharge->getId());
  1713.             $colors["$date_f"] = ['date' => $date_f'background' => $priceSurcharge->getColor(), 'textcolor' => $priceSurcharge->getTextColor(), 'name' => $priceSurcharge->getName(), 'price_surcharge' => $priceSurcharge->getId(), 'price' => '€ ' $priceSurcharge->getPriceMinute()];
  1714.             $labels_index["$date_f"] = $priceSurcharge->getId();
  1715.             if (empty($priceSurchargeNext)) {
  1716.                 $max_days $max_available_days;
  1717.             } else {
  1718.                 $max_days $priceSurchargeNext->getDays();
  1719.             }
  1720.             $max_days = (int)$max_days;
  1721.             for ($i 1$i <= $max_days$i++) {
  1722.                 //$date_initial->add(new \DateInterval('P1D'));
  1723.                 $date_initial $this->AddDateExcludeWeekends($date_initial1);
  1724.                 $date_f $date_initial->format('Y-m-d');
  1725.                 $date_fi str_replace("-"""$date_f);
  1726.                 //echo $date_f."\n";
  1727.                 $labels["$date_f"] = ['start' => $date_f'price_surcharge' => $priceSurcharge->getId()];
  1728.                 //$labels[$date_f] = array('start'=>$date_f,'title'=>'$ '.$priceSurcharge->getPriceMinute(),'price_surcharge'=>$priceSurcharge->getId());
  1729.                 $colors["$date_f"] = ['date' => $date_f'background' => $priceSurcharge->getColor(), 'textcolor' => $priceSurcharge->getTextColor(), 'name' => $priceSurcharge->getName(), 'price_surcharge' => $priceSurcharge->getId(), 'price' => '€ ' $priceSurcharge->getPriceMinute()];
  1730.                 $labels_index["$date_f"] = $priceSurcharge->getId();
  1731.             }
  1732.             $priceSurcharge $priceSurchargeNext;
  1733.         }
  1734.         for ($i 0$i $addition_days$i++) {
  1735.             array_shift($labels);
  1736.             array_shift($colors);
  1737.             array_shift($labels_index);
  1738.         }
  1739.         $labels_copy $labels;
  1740.         reset($labels_copy);
  1741.         $min key($labels_copy);
  1742.         /** @var Setting $setting */
  1743.         $setting $this->getDoctrine()->getRepository(Setting::class)->find(12);
  1744.         $setting_value json_decode($setting->getValue(), true);
  1745.         $customer =  $wicam_header->getCustomer();
  1746.         $minimum_value 0;
  1747.         if(!is_null($customer)){
  1748.             $customer_category $customer->getCategory()->getDescription();
  1749.         } else {
  1750.             $customer_category 'no_category';
  1751.         }
  1752.         foreach($setting_value as $k=>$s){
  1753.             $categoryDescription str_replace('category_','',$k);
  1754.             if($categoryDescription == $customer_category){
  1755.                 $minimum_value $s 1.0;
  1756.             }
  1757.         }
  1758.         if($minimum_value == 0){
  1759.             $customer_category 'no_category';
  1760.             foreach($setting_value as $k=>$s){
  1761.                 $categoryDescription str_replace('category_','',$k);
  1762.                 if($categoryDescription == $customer_category){
  1763.                     $minimum_value $s 1.0;
  1764.                 }
  1765.             }
  1766.         }
  1767.         $new_labels = [];
  1768.         foreach ($labels as $lb) {
  1769.             $new_labels[] = $lb;
  1770.         }
  1771.         $new_colors = [];
  1772.         $is_first_price_surcharge true;
  1773.         $first_price_surcharge 0;
  1774.         foreach ($colors as $lb) {
  1775.             $new_colors[] = $lb;
  1776.             $totals $this->getDoctrine()->getManager()->getRepository(WiCamFilesPriceSurcharge::class)->findTotalByWiCamHeader($wicam_header_id$lb['price_surcharge']);
  1777.             $totals += $qbTotals['total'];
  1778.             $totals += $wicam_header->getDeliveryCost();
  1779.             $totals $totals <= $minimum_value $minimum_value $totals;
  1780.             //$legends_colors[$lb['price_surcharge']] = array($lb['background'],$lb['price']);
  1781.             $value_m number_format($totals2',''.');
  1782.             if ($request->getLocale() == 'en') {
  1783.                 $value_m $this->currencySymbol ' ' $value_m;
  1784.             } else {
  1785.                 $value_m $value_m ' ' $this->currencySymbol;
  1786.             }
  1787.             $legends_colors[$lb['price_surcharge']] = [$lb['background'], $value_m, (empty($lb['name']) ? '&nbsp;' $lb['name']), $lb['textcolor']];
  1788.             if ($is_first_price_surcharge) {
  1789.                 $is_first_price_surcharge false;
  1790.                 $first_price_surcharge $lb['price_surcharge'];
  1791.             }
  1792.         }
  1793.         // Set invalid parameters
  1794.         $invalid = [];
  1795.         $invalid[] = ['recurring' => ['repeat' => 'weekly''weekDays' => 'SA,SU']];
  1796.         // add holidays
  1797.         $holidays $this->getDoctrine()->getRepository(Holiday::class)->findAllHolidaysFromNow();
  1798.         if ($holidays) {
  1799.             foreach ($holidays as $h) {
  1800.                 $hd $h->getDate();
  1801.                 $invalid[] = $hd->format('Y-m-d');
  1802.             }
  1803.         }
  1804.         $max $date_initial->format('Y-m-d');
  1805.         return new JsonResponse(['labels' => $new_labels'colors' => $new_colors'labels_index' => $labels_index'legends_colors' => $legends_colors'invalid' => $invalid'min' => $min'max' => $max'first_price_surcharge' => $first_price_surcharge'cutting_time' => $sum_cutting_time]);
  1806.     }
  1807.     private function AddDateExcludeWeekends($date_initial$number)
  1808.     {
  1809.         $date_initial->add(new \DateInterval('P' $number 'D'));
  1810.         $dayOfWeek date('w'strtotime($date_initial->format('Y-m-d')));
  1811.         $holiday $this->getDoctrine()->getRepository(Holiday::class)->findOneByDateFromNow($date_initial->format('Y-m-d'));
  1812.         while ($dayOfWeek == || $dayOfWeek == || !empty($holiday)) {
  1813.             $date_initial->add(new \DateInterval('P1D'));
  1814.             $dayOfWeek date('w'strtotime($date_initial->format('Y-m-d')));
  1815.             $holiday $this->getDoctrine()->getRepository(Holiday::class)->findOneByDateFromNow($date_initial->format('Y-m-d'));
  1816.             //echo 'Add new date-> '.$date_initial->format('Y-m-d')." - ".$dayOfWeek."\n";
  1817.         }
  1818.         return $date_initial;
  1819.     }
  1820.     /**
  1821.      * @Route("/upload/wicam_files_surcharges",  methods={"POST"}, name="wi_cam_files_surcharges")
  1822.      * @param Request $request
  1823.      *
  1824.      * @return JsonResponse
  1825.      */
  1826.     public function WiCamFilesSurcharges(Request $request): JsonResponse
  1827.     {
  1828.         $wicam_file_id $request->get("wicam_file");
  1829.         $identify $request->get("identify");
  1830.         $type $request->get("type");
  1831.         $entityManager $this->getDoctrine()->getManager();
  1832.         $w_surcharges $entityManager->getRepository(WiCamFilesSurcharges::class)->findBy(['wicam_files' => $wicam_file_id'surcharges' => $identify]);
  1833.         if (!empty($w_surcharges)) {
  1834.             foreach ($w_surcharges as $sch) {
  1835.                 $entityManager->remove($sch);
  1836.             }
  1837.         }
  1838.         if ($type == 'add') {
  1839.             $surcharges $entityManager->getRepository(Surcharges::class)->find($identify);
  1840.             $wicam_file $entityManager->getRepository(WiCamFiles::class)->find($wicam_file_id);
  1841.             if($wicam_file->getWicamHeader()->getCustomer() != null && $wicam_file->getWicamHeader()->getCustomer()->getCategory() != null){
  1842.                 $category_id $wicam_file->getWicamHeader()->getCustomer()->getCategory();
  1843.             } else {
  1844.                 $category_id null;
  1845.             }
  1846.             if($surcharges != null){
  1847.                 $surcharges_id $surcharges;
  1848.             } else {
  1849.                 $surcharges_id null;
  1850.             }
  1851.             $surcharges_category $entityManager->getRepository(SurchargesCategory::class)->findOneBy(['category_id' => $category_id'surcharges_id' => $surcharges_id]);
  1852.             /** @var WiCamFilesSurcharges $wicam_files_surcharges */
  1853.             $wicam_files_surcharges = new WiCamFilesSurcharges();
  1854.             $wicam_files_surcharges->setWicamFiles($wicam_file)
  1855.                 ->setSurcharges($surcharges)
  1856.                 ->setSurchargesCategory($surcharges_category);
  1857.             $entityManager->persist($wicam_files_surcharges);
  1858.         }
  1859.         $entityManager->flush();
  1860.         return new JsonResponse(['status' => true]);
  1861.     }
  1862.     /**
  1863.      * @Route("/upload/multiple_surcharges",  methods={"POST"}, name="multiple_surcharges")
  1864.      * @param Request $request
  1865.      *
  1866.      * @return JsonResponse
  1867.      */
  1868.     public function MultipleSurcharges(Request $request): JsonResponse
  1869.     {
  1870.         $entityManager $this->getDoctrine()->getManager();
  1871.         $header_id $request->get("header_id");
  1872.         $surcharges $request->get("data");
  1873.         /** @var WiCamHeader $wicam_header */
  1874.         /** @var WiCamFiles $wicamFile */
  1875.         $wicam_header $entityManager->getRepository(WiCamHeader::class)->find($header_id);
  1876.         foreach ($wicam_header->getWicamFiles() as $wicamFile) {
  1877.             /** @var WiCamFilesSurcharges $ws */
  1878.             foreach ($wicamFile->getWiCamFilesSurcharges() as $ws) {
  1879.                 if ($ws->getSurcharges()->getAllowToApplyAll()) {
  1880.                     $entityManager->remove($ws);
  1881.                 }
  1882.             }
  1883.             /** @var WiCamFilesSurcharges $wicamsurcharge */
  1884.             if (count($surcharges) > 0) {
  1885.                 /** @var Surcharges $surcharge */
  1886.                 foreach ($surcharges as $surch) {
  1887.                     $surcharge $entityManager->getRepository(Surcharges::class)->find($surch);
  1888.                     if($surcharge != null){
  1889.                         $surcharge_id $surcharge;
  1890.                     } else {
  1891.                         $surcharge_id null;
  1892.                     }
  1893.                     if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null) {
  1894.                         $category_id $wicam_header->getCustomer()->getCategory();
  1895.                     } else {
  1896.                         $category_id null;
  1897.                     }
  1898.                     $surcharge_category $entityManager->getRepository(SurchargesCategory::class)->findOneBy(['category_id' => $category_id'surcharges_id' => $surcharge_id]);
  1899.                     $wicamsurcharge = new WiCamFilesSurcharges();
  1900.                     $wicamsurcharge->setWicamFiles($wicamFile);
  1901.                     $wicamsurcharge->setSurcharges($surcharge);
  1902.                     $wicamsurcharge->setSurchargesCategory($surcharge_category);
  1903.                     $entityManager->persist($wicamsurcharge);
  1904.                 }
  1905.             }
  1906.         }
  1907.         $entityManager->flush();
  1908.         return new JsonResponse(['msg' => 'done']);
  1909.     }
  1910.     /**
  1911.      * @Route("/upload/get_diameter_hole",  methods={"POST"}, name="wi_cam_get_diameters")
  1912.      * @param Request $request
  1913.      *
  1914.      * @return JsonResponse
  1915.      */
  1916.     public function getDiameterHoles(Request $request): JsonResponse
  1917.     {
  1918.         $thickness $request->get('thickness');
  1919.         $amount $request->get('amount');
  1920.         $identify $request->get('identify');
  1921.         /** @var Thickness $thick */
  1922.         $thick $this->getDoctrine()->getRepository(Thickness::class)->find($thickness);
  1923.         $thickness_value $thick->getValue();
  1924.         $wicam_file_circles $this->getDoctrine()->getRepository(WiCamFilesCircles::class)->findBy(['wicam_files' => $identify]);
  1925.         $html_response = [];
  1926.         if ($wicam_file_circles) {
  1927.             /** @var WiCamFilesCircles $wicam_circle */
  1928.             foreach ($wicam_file_circles as $wicam_circle) {
  1929.                 $diameters $this->getDoctrine()->getRepository(DiameterHole::class)->findByThicknessAmount($thickness_value$wicam_circle->getAmount());
  1930.                 $html $this->renderView('includes/wicam-diameter-hole.html.twig', ['diameters' => $diameters]);
  1931.                 $html_response[$wicam_circle->getDiameter()]['html'] = $html;
  1932.                 $html_response[$wicam_circle->getDiameter()]['count'] = count($diameters);
  1933.             }
  1934.         }
  1935.         return new JsonResponse([
  1936.             'html_response'   => $html_response,
  1937.             'thickness_value' => $thickness_value
  1938.         ]);
  1939.     }
  1940.     /**
  1941.      * @Route("/upload/set_circle_data",  methods={"POST"}, name="wi_cam_get_circle_data")
  1942.      * @param Request $request
  1943.      *
  1944.      * @return JsonResponse
  1945.      */
  1946.     public function setWiCamFilesCircles(Request $request): JsonResponse
  1947.     {
  1948.         $identify $request->get('identify');
  1949.         $diameter $request->get('diameter');
  1950.         $technology $request->get('technology');
  1951.         $diameter_hole_id $request->get('diameter_hole');
  1952.         $wicam_file $this->getDoctrine()->getRepository(WiCamFiles::class)->find($identify);
  1953.         /** @var WiCamFilesCircles $WiCamCircle */
  1954.         $manager $this->getDoctrine()->getManager();
  1955.         $WiCamCircle $manager->getRepository(WiCamFilesCircles::class)->findOneByWiCamFileDiameter($identify$diameter);
  1956.         $response = ['not done'];
  1957.         if (!empty($diameter_hole_id)) {
  1958.             $diameter_hole $this->getDoctrine()->getRepository(DiameterHole::class)->find($diameter_hole_id);
  1959.             $WiCamCircle->setDiameterHole($diameter_hole);
  1960.             $response = ['done'];
  1961.         } else {
  1962.             $WiCamCircle->setDiameterHole(null);
  1963.             $response = ['done'];
  1964.         }
  1965.         if (!empty($technology)) {
  1966.             $WiCamCircle->setTechnology($technology);
  1967.             if ($technology == 1) {
  1968.                 $WiCamCircle->setDiameterHole(null);
  1969.             }
  1970.             $response = ['done'];
  1971.         }
  1972.         $manager->flush();
  1973.         return new JsonResponse($response);
  1974.     }
  1975.     /**
  1976.      * @Route("/upload/print_offer",  methods={"POST","GET"}, name="wi_cam_print_offer")
  1977.      * @param Request $request
  1978.      *
  1979.      * @return Response
  1980.      */
  1981.     public function print_offer(Request $request)
  1982.     {
  1983.         $header_id $request->get('code-of');
  1984.         //dump($header_id);
  1985.         $response $this->printOffer($header_id$request->getLocale());
  1986.         //dump($response);
  1987.         $filename $response['filename'];
  1988.         $pdf $response['pdf'];
  1989.         $pdf->Output($filename'I');
  1990.         /*return new JsonResponse(array("path"=>'/offerFiles/'.$filename,
  1991.             "realname"=>$filename));*/
  1992.         return new Response();
  1993.     }
  1994.     public function printOffer($header_id$locale$return false)
  1995.     {
  1996.         if (empty($header_id)) {
  1997.             return $this->redirectToRoute('wi_cam_home');
  1998.         }
  1999.         // $header_id = 502;
  2000.         $entityManager $this->getDoctrine()->getManager();
  2001.         /** @var WiCamHeader $wicam_heafder */
  2002.         /** @var WiCamFiles $wicam_files */
  2003.         $wicam_header $entityManager->getRepository(WiCamHeader::class)->find($header_id);
  2004.         if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null) {
  2005.             $total_data $this->GetBuyBox($wicam_header->getGuid(), $header_idtrue$wicam_header->getCustomer()->getCategory()->getId());
  2006.         } else {
  2007.             $total_data $this->GetBuyBox($wicam_header->getGuid(), $header_idtruenull);
  2008.         }
  2009.         /*return array('total' => $result['total'],
  2010.             'wicamheader' => $wiCamHeader,
  2011.             'surcharges' => $qb,
  2012.             'minimun'=>$setting);*/
  2013.         $wicam_files $entityManager->getRepository(WiCamFiles::class)->findBy(['wicam_header' => $header_id'validation' => 1'deleted' => 0], ['orden' => 'ASC']);
  2014.         $total $entityManager->getRepository(WiCamFilesPriceSurcharge::class)->findTotalByWiCamHeader($header_id$wicam_header->getPriceSurcharge()->getId());
  2015.         $offer_text $entityManager->getRepository(Setting::class)->find(self::SETTING_OFFER_TEXT);
  2016.         $vatPercent $entityManager->getRepository(Setting::class)->find(static::VAT_PERCENT)->getValue();
  2017.         $offer_text unserialize($offer_text->getValue());
  2018.         $offer_text $offer_text[$locale];
  2019.         $defaultId $entityManager->getRepository(Setting::class)->find(self::DEFAULT_REPRESENTATIVE);
  2020.         $defaultRepresentative $entityManager->getRepository(Representative::class)->find($defaultId->getValue());
  2021.         /** @var Setting $setting */
  2022.         $setting $entityManager->getRepository(Setting::class)->find(self::MAX_DRILLING_DIAMETER_ID);
  2023.         // dump($defaultRepresentative);
  2024.         // Retrieve the HTML generated in our twig file
  2025.         $html $this->renderView('wicam/print-offer.html.twig', [
  2026.             'wicam_header'          => $wicam_header,
  2027.             'wicam_files'           => $wicam_files,
  2028.             'totalsum'              => $total,
  2029.             'total'                 => $total_data['total'],
  2030.             'vatPercent'            => $vatPercent,
  2031.             'wicamheader'           => $total_data['wicamheader'],
  2032.             'surcharges'            => $total_data['surcharges'],
  2033.             'minimun'               => $total_data['minimun'],
  2034.             'offer_text'            => $offer_text,
  2035.             'defaultRepresentative' => $defaultRepresentative,
  2036.             'MAX_DRILLING_DIAMETER' => $setting->getValue()
  2037.         ]);
  2038.         $pdf = new PrintOffer();
  2039.         $html_header $this->renderView('wicam/print-header-offer.html.twig', [
  2040.             'header' => ''
  2041.         ]);
  2042.         $html_footer $this->renderView('wicam/print-footer-offer.html.twig', [
  2043.             'footer' => ''
  2044.         ]);
  2045.         $pdf->htmlHeader $html_header;
  2046.         $pdf->htmlFooter $html_footer;
  2047.         //$pdf->SetMargins(0.3,0.3,0.2,20);// left, top, right
  2048.         $pdf->startPageGroup();
  2049.         $pdf->SetMargins(2036); //left, top, right
  2050.         $pdf->setHeaderMargin(12);
  2051.         $pdf->SetAutoPageBreak(true40);
  2052.         $pdf->AddPage('P''A4');
  2053.         //$pdf->AddPage('L', 'A4');
  2054.         // Retrieve the HTML generated in our twig file
  2055.         //echo $html;
  2056.         //die;
  2057.         $pdf->writeHTML($htmltruefalsefalsefalse'');
  2058.         $pdf->lastPage();
  2059.         $orderNumber $wicam_header->getOrderNumber();
  2060.         if ($orderNumber 0) {
  2061.             $filename "Order" "_" $wicam_header->getOrderNumber() . ".pdf";
  2062.         } else {
  2063.             $filename "Offer" "_" $wicam_header->getId() . ".pdf";
  2064.         }
  2065.         ob_clean();
  2066.         $publicDirectory $this->getParameter('kernel.project_dir') . '/public/offerFiles';
  2067.         if ($return) {
  2068.             $realDirectory $publicDirectory '/' $filename;
  2069.             $pdf->Output($realDirectory'F');
  2070.             return ['path' => $realDirectory];
  2071.         } else {
  2072.             return ['filename' => $filename'pdf' => $pdf];
  2073.         }
  2074.     }
  2075.     /**
  2076.      * @Route("/upload/update_positions",  methods={"POST"}, name="wi_cam_update_positions")
  2077.      * @param Request $request
  2078.      *
  2079.      * @return JsonResponse
  2080.      */
  2081.     public function update_positions(Request $request): JsonResponse
  2082.     {
  2083.         $positions $request->get('positions');
  2084.         $entityManager $this->getDoctrine()->getManager();
  2085.         if (!empty($positions)) {
  2086.             foreach ($positions as $item) {
  2087.                 $id $item['identify'];
  2088.                 $orden $item['order'];
  2089.                 /** @var WiCamFiles $wf */
  2090.                 $wf $entityManager->getRepository(WiCamFiles::class)->find($id);
  2091.                 $wf->setOrden($orden);
  2092.                 $entityManager->flush();
  2093.             }
  2094.         }
  2095.         return new JsonResponse(['msg' => 'update_positions']);
  2096.     }
  2097.     /**
  2098.      * @Route("/upload/orderNow", name="wi_cam_create_order")
  2099.      * @param Request          $request
  2100.      * @param WicamOrderHelper $wicamOrderHelper
  2101.      *
  2102.      * @return JsonResponse
  2103.      */
  2104.     public function create_order(Request $requestWicamOrderHelper $wicamOrderHelper): Response
  2105.     {
  2106.         if ($this->getUser()) {
  2107.             $wicamOrderHelper->setLocale($request->getLocale());
  2108.             $parameters = [];
  2109.             if (isset($_COOKIE['wsCode'])) {
  2110.                 $wsCode $_COOKIE['wsCode'];
  2111.                 if (!empty($wsCode)) {
  2112.                     if (is_numeric($wsCode)) {
  2113.                         $wsCodeEn $this->encryptor->encrypt($wsCode);
  2114.                         setcookie('wsCode'$wsCodeEntime() + 604800'/');
  2115.                     } else {
  2116.                         $wsCode $this->encryptor->decrypt($wsCode);
  2117.                     }
  2118.                     $parameters $wicamOrderHelper->OfferToOrder($wsCode);
  2119.                     //$parameters = array('status'=>true,'orderNumber'=>1,'type_error'=>'');
  2120.                     if ($parameters['status']) {
  2121.                         $vatPercent $this->getDoctrine()->getRepository(Setting::class)->find(static::VAT_PERCENT)->getValue();
  2122.                         $wicamHeader $this->getDoctrine()->getRepository(WiCamHeader::class)->find($wsCode);
  2123.                         $WiCamFiles $this->getDoctrine()->getRepository(WiCamFiles::class)->findByHeader($wsCode);
  2124.                         $parameters['wicamHeader'] = $wicamHeader;
  2125.                         $parameters['WiCamFiles'] = $WiCamFiles;
  2126.                         if($wicamHeader->getCustomer() != null && $wicamHeader->getCustomer()->getCategory() != null) {
  2127.                             $total_data $this->GetBuyBox($wicamHeader->getGuid(), $wicamHeader->getId(), true$wicamHeader->getCustomer()->getCategory()->getId());
  2128.                         } else {
  2129.                             $total_data $this->GetBuyBox($wicamHeader->getGuid(), $wicamHeader->getId(), truenull);
  2130.                         }
  2131.                         //$total_data = $this->GetBuyBox($wicamHeader->getGuid(), $wicamHeader->getId(), true,$wicamHeader->getCustomer()->getCategory()->getId());
  2132.                         $parameters['wicamheader'] = $total_data['wicamheader'];
  2133.                         $parameters['surcharges'] = $total_data['surcharges'];
  2134.                         $parameters['minimun'] = $total_data['minimun'];
  2135.                         $parameters['total'] = $total_data['total'];
  2136.                         $parameters['vatPercent'] = $vatPercent;
  2137.                         // destroy cookie if the offer it correctly converted
  2138.                         setcookie("wsCode"""time() - 3600'/');
  2139.                     }
  2140.                 }
  2141.             } else {
  2142.                 $parameters = ['status' => false'type_error' => 'NOTHING_TO_ORDER'];
  2143.             }
  2144.             return $this->render('checkout/checkout-wicam.html.twig'$parameters);
  2145.         } else {
  2146.             return $this->redirectToRoute('app_login', ['referer' => $this->generateUrl('wi_cam_home')]);
  2147.         }
  2148.     }
  2149.     public function orders(Request $requestAdminOrdersController $adminOrdersControllerPaginatorInterface $paginator): Response
  2150.     {
  2151.         if (!$this->getUser()) {
  2152.             return $this->redirectToRoute('app_login');
  2153.         }
  2154.         $are_orders = empty($request->get('are_orders')) ? false $request->get('are_orders');
  2155.         $data = [];
  2156.         $itemsPerPage 10;
  2157.         /** @var User $user */
  2158.         $user $this->getUser();
  2159.         if (count($user->getUserRepresentatives()) > 0) {
  2160.             /** @var UserRepresentative $userRepresentative */
  2161.             $userRepresentative $user->getUserRepresentatives()[0];
  2162.             $data['representative'] = $userRepresentative->getRepresentative()->getId();
  2163.             $sort = !empty($request->get('sort')) ? $request->get('sort') : "wh.orderNumber";
  2164.             $direction = !empty($request->get('direction')) ? $request->get('direction') : "desc";
  2165.             $orders $adminOrdersController->GetOrders($data$sort$directionfalse$are_orders);
  2166.         } else if ($user->getActiveCustomerForUserCustomer()) {
  2167.             $data['customer'] = $user->getActiveCustomerForUserCustomer();
  2168.             $sort = !empty($request->get('sort')) ? $request->get('sort') : "wh.orderNumber";
  2169.             $direction = !empty($request->get('direction')) ? $request->get('direction') : "desc";
  2170.             $orders $adminOrdersController->GetOrders($data$sort$directionfalse$are_orders);
  2171.         } else {
  2172.             $orders = [];
  2173.         }
  2174.         $pagination $paginator->paginate(
  2175.             $orders/* query NOT result */
  2176.             $request->get("page"1),
  2177.             $itemsPerPage/*limit per page*/
  2178.             ['wrap-queries' => true]
  2179.         );
  2180.         return $this->render(
  2181.             'account/orders.html.twig', [
  2182.                 'popup_message' => getenv("ENVIRONMENT"),
  2183.                 'are_orders'    => $are_orders,
  2184.                 'orders'        => $orders,
  2185.                 'pagination'    => $pagination
  2186.             ]
  2187.         );
  2188.     }
  2189.     /**
  2190.      * @Route("/upload/reload-entry", name="wi_cam_reload_entry")
  2191.      * @param Request $request
  2192.      *
  2193.      * @return JsonResponse
  2194.      */
  2195.     public function reloadOrder(Request $requestWicamOrderHelper $wicamOrderHelper): JsonResponse
  2196.     {
  2197.         if (!$this->getUser()) {
  2198.             die();
  2199.         }
  2200.         /** @var WiCamHeaderTemp $wh */
  2201. //        $wh = $this->getDoctrine()->getRepository(WiCamHeaderTemp::class)->find($request->get('id'));
  2202. //        var_dump($request->get('id'));
  2203. //        var_dump($wh);
  2204.         /** @var WiCamHeader $wicamHeader */
  2205.         $wicamHeader $this->getDoctrine()->getRepository(WiCamHeader::class)->find($request->get('id'));
  2206. //        var_dump($wicamHeader);
  2207.         $sendEmail $request->get('sendEmail');
  2208.         $sendEmail $sendEmail == 'true' true false;
  2209. //        $representativeId = $wh->getRepresentativeId();
  2210. //        $representative = $this->getDoctrine()->getRepository(Representative::class)->find($representativeId);
  2211.         if ($wicamHeader->getIsOrder()) {
  2212.             if ($sendEmail) {
  2213.                 $wicamOrderHelper->SendEmailOrder($wicamHeader->getRepresentative(), $wicamHeader);
  2214.             }
  2215.         }
  2216.         $html $this->renderView('account/order-entry.html.twig', ['wh' => $wicamHeader'are_orders' => $wicamHeader->getIsOrder()]);
  2217.         // var_dump($html);
  2218.         return new JsonResponse(['html' => $html]);
  2219.     }
  2220.     /**
  2221.      * @Route("/upload/convert-order", name="wi_cam_convertorder")
  2222.      * @param Request          $request
  2223.      * @param WicamOrderHelper $orderWicamHelper
  2224.      *
  2225.      * @return JsonResponse
  2226.      */
  2227.     function ConvertToOrder(Request $requestWicamOrderHelper $orderWicamHelper): JsonResponse
  2228.     {
  2229.         $id $request->get("id");
  2230.         $orderWicamHelper->setLocale($request->getLocale());
  2231.         return new JsonResponse($orderWicamHelper->OfferToOrder($idfalse));
  2232.     }
  2233.     /**
  2234.      * @param WiCamFiles          $wicam_file
  2235.      * @param Thickness           $thickness
  2236.      * @param SurchargeDimensions $surcharge_dimension
  2237.      * @param Setting             $setting_specific_weight
  2238.      *
  2239.      * @return float
  2240.      */
  2241.     private function getTotalWeight(
  2242.         WiCamFiles          $wicam_file,
  2243.         Thickness           $thickness,
  2244.         SurchargeDimensions $surcharge_dimension,
  2245.         Setting             $setting_specific_weight): float
  2246.     {
  2247.         $width $wicam_file->getWidth();
  2248.         $length $wicam_file->getLength();
  2249.         $thickness_vl $thickness->getValue() * 1.0;
  2250.         $width_s $surcharge_dimension->getWidth() * 1.0;
  2251.         $specific_weight $setting_specific_weight->getValue() * 1.0;
  2252.         $pre_weight $thickness_vl * ($width $width_s) * ($length $width_s) * $specific_weight;
  2253.         $pre_weight $pre_weight 1000000;
  2254.         return $pre_weight * ($thickness->getScrapFactor() * 1.0);
  2255.     }
  2256.     /**
  2257.      * @param array $surcharges_handlings
  2258.      * @param $total_weight
  2259.      * @param $amount
  2260.      * @param $customer
  2261.      *
  2262.      * @return float|null
  2263.      */
  2264.     private function getAddtionalHandling(array $surcharges_handlings$total_weight$amount,
  2265.                                           $customer): ?float
  2266.     {
  2267.         $entityManager $this->getDoctrine()->getManager();
  2268.         $additional_handling 0.0;
  2269.         if ($surcharges_handlings) {
  2270.             /** @var SurchargeHandling $sh */
  2271.             foreach ($surcharges_handlings as $sh) {
  2272.                 $filter_operator_to '';
  2273.                 $filter_operator_to_pi '';
  2274.                 if (!empty($sh->getWeightTo()) && !empty($sh->getOperatorTo())) {
  2275.                     $filter_operator_to ' && ' $total_weight $sh->getOperatorTo() . $sh->getWeightTo();
  2276.                 }
  2277.                 if ($sh->getPiecesValidation()) {
  2278.                     if (!empty($sh->getNumberPiecesTo()) && !empty($sh->getOperatorPiecesTo())) {
  2279.                         $filter_operator_to_pi ' && ' $amount $sh->getOperatorPiecesTo() . $sh->getNumberPiecesTo();
  2280.                     }
  2281.                     eval('$res = ' $total_weight $sh->getOperator() . $sh->getWeight() . $filter_operator_to ' && ' $amount $sh->getOperatorPieces() . $sh->getNumberPieces() . $filter_operator_to_pi ';');
  2282.                 } else {
  2283.                     eval(' $res = ' $total_weight $sh->getOperator() . $sh->getWeight() . $filter_operator_to ';');
  2284.                 }
  2285.                 if ($res) {
  2286.                     $surcharges_handlings_category_repository $entityManager->getRepository(SurchargesHandlingCategory::class);
  2287.                     if(!is_null($customer)){
  2288.                         if(!is_null($customer->getCategory())){
  2289.                             $surcharges_handlings_category $surcharges_handlings_category_repository->findOneBy(['surcharges_handling_id' => $sh->getId(), 'category_id' => $customer->getCategory()->getId()]);
  2290.                             $customer_category $customer->getCategory()->getDescription();
  2291.                             $surchargeHandlingCategory $surcharges_handlings_category->getCategory()->getDescription();
  2292.                             if($customer_category == $surchargeHandlingCategory){
  2293.                                 $additional_handling += $surcharges_handlings_category->getPercent();
  2294.                             }
  2295.                         } else {
  2296.                             $surcharges_handlings_category $surcharges_handlings_category_repository->findOneBy(['surcharges_handling_id' => $sh->getId()]);
  2297.                             $customer_category 'no_category';
  2298.                             $additional_handling += $surcharges_handlings_category->getPercent();
  2299.                         }
  2300.                     } else {
  2301.                         $surcharges_handlings_category $surcharges_handlings_category_repository->findOneBy(['surcharges_handling_id' => $sh->getId()]);
  2302.                         $customer_category 'no_category';
  2303.                         $additional_handling += $surcharges_handlings_category->getPercent();
  2304.                     }
  2305.                 }
  2306.             }
  2307.         }
  2308.         return ($additional_handling 100) + 1;
  2309.     }
  2310.     /**
  2311.      * @param WiCamFiles $wicam_file
  2312.      * @param            $thickness_id
  2313.      * @param            $material_grade_id
  2314.      *
  2315.      * @return float|null
  2316.      */
  2317.     private function getPriceMaterialAndSurcharges(WiCamFiles $wicam_file$thickness_id$material_grade_id): ?float
  2318.     {
  2319.         $entityManager $this->getDoctrine()->getManager();
  2320.         /** @var MaterialPrices $material_prices */
  2321.         $MaterialPrices $entityManager->getRepository(MaterialPrices::class)->findOneByThicknessMaterial($thickness_id$material_grade_id);
  2322.         $totalMaterialPrices $MaterialPrices->getValue() * 1.0;
  2323.         $surcharges $wicam_file->getWiCamFilesSurcharges();
  2324.         if (!empty($surcharges)) {
  2325.             /** @var WiCamFilesPriceSurcharge $sh */
  2326.             foreach ($surcharges as $sh) {
  2327.                 if ($sh->getSurcharges()->getPriceForm() == self::EUR_PER_TON) {
  2328.                     $surchargesThickness $entityManager->getRepository(SurchargesThickness::class)->findBy(['thickness' => $thickness_id'surcharges' => $sh->getSurcharges()->getId()]);
  2329.                     if (!empty($surchargesThickness)) {
  2330.                         /** @var SurchargesThickness $st */
  2331.                         foreach ($surchargesThickness as $st) {
  2332.                             $totalMaterialPrices += $st->getValue();
  2333.                         }
  2334.                     }
  2335.                 }
  2336.             }
  2337.         }
  2338.         return $totalMaterialPrices;
  2339.     }
  2340.     /**
  2341.      * @param WiCamFiles $wicam_file
  2342.      * @param Setting    $setting_max_drilling
  2343.      * @param            $thickness_id
  2344.      *
  2345.      * @return float
  2346.      */
  2347.     private function getCuttingTime(WiCamFiles $wicam_fileSetting $setting_max_drilling$thickness_id): float
  2348.     {
  2349.         $entityManager $this->getDoctrine()->getManager();
  2350.         $REDUCTION_CUTTING_TIME 0.0;
  2351.         $REDUCING_CONTURS 0.0;
  2352.         $contours $wicam_file->getContours();
  2353.         $cutLenght $wicam_file->getTotalLenght();
  2354.         /** @var FeedData $feed_data */
  2355.         $feed_data $entityManager->getRepository(FeedData::class)->findOneByThickness($thickness_id);
  2356.         $mm_min $feed_data->getMmMin() * 1.0;
  2357.         $punching_time $feed_data->getPunchingTime() * 1.0;
  2358.         $circles $wicam_file->getWiCamFilesCircles();
  2359.         if (!empty($circles)) {
  2360.             /** @var WiCamFilesCircles $cl */
  2361.             foreach ($circles as $cl) {
  2362.                 if ($cl->getTechnology() == || $cl->getTechnology() == || $cl->getDiameter() >= $setting_max_drilling->getValue()) {
  2363.                     $REDUCTION_CUTTING_TIME += $cl->getDiameter() * M_PI $cl->getAmount();
  2364.                     $REDUCING_CONTURS += $cl->getAmount();
  2365.                 }
  2366.             }
  2367.         }
  2368.         $REDUCTION_CUTTING_TIME round($REDUCTION_CUTTING_TIME2);
  2369.         return ((($cutLenght $REDUCTION_CUTTING_TIME) / $mm_min) + ((($contours $REDUCING_CONTURS) * $punching_time) / 60));
  2370.     }
  2371.     /**
  2372.      * @param $header_id
  2373.      *
  2374.      * @return float
  2375.      */
  2376.     private function getAdditionalValueCircle($header_id): float
  2377.     {
  2378.         /** @var EntityRepository $repository */
  2379.         $repository $this->getDoctrine()->getRepository(WiCamFilesCircles::class);
  2380.         $qb $repository->createQueryBuilder('ws');
  2381.         $qb $qb
  2382.             ->select('COALESCE(SUM(dh.value * ws.amount),0.0) as total')
  2383.             ->innerJoin('ws.wicam_files''wf')
  2384.             ->innerJoin('ws.diameter_hole''dh')
  2385.             ->where('wf.wicam_header = :wicam_header')
  2386.             ->andWhere('ws.technology = :technology')
  2387.             ->setParameter('wicam_header'$header_id)
  2388.             ->setParameter('technology'2)
  2389.             ->getQuery()
  2390.             ->getResult();
  2391.         return $qb[0]['total'];
  2392.     }
  2393.     /**
  2394.      * @param WiCamFiles $wicam_file
  2395.      *
  2396.      * @return void
  2397.      */
  2398.     private function deleteWiCamFilesPriceSurcharge(WiCamFiles $wicam_file)
  2399.     {
  2400.         $entityManager $this->getDoctrine()->getManager();
  2401.         $query $entityManager->createQuery(
  2402.             'DELETE
  2403.                     FROM App\Entity\WiCamFilesPriceSurcharge p
  2404.                     WHERE p.wicam_files = :wicam_file'
  2405.         )->setParameter('wicam_file'$wicam_file->getId());
  2406.         $query->getResult();
  2407.     }
  2408.     /**
  2409.      * @Route("/upload/test-email", name="wi_cam_test-email")
  2410.      * @param Request         $request
  2411.      * @param MailerInterface $mailer
  2412.      *
  2413.      * @return JsonResponse
  2414.      */
  2415.     function TestEmail(Request $request,MailerInterface $mailer):JsonResponse{
  2416.     $email = (new Email())
  2417.         ->from('info@cad2cut.de')
  2418.         ->to('ibarragan2004@hotmail.com');
  2419.     $email->subject("Test")
  2420.         ->html("test");
  2421.         $status false;
  2422.         $msg '';
  2423.         try {
  2424.             $mailer->send($email);
  2425.             $status true;
  2426.             $msg $this->translator->trans("The email has been sended");
  2427.         } catch (TransportExceptionInterface $e) {
  2428.             $msg $e->getMessage();
  2429.         }
  2430.         echo $msg;
  2431.         die;
  2432.         return new JsonResponse(['msg' => $msg]);
  2433.     }
  2434.     public function getArrayAddress(User $user): array
  2435.     {
  2436.         $userAddresses $user->getAddresses();
  2437.         if (!$user->getUseBillingAddressAsShippingAddress() and count($userAddresses) > 0) {
  2438.             /** @var UserAddress $address */
  2439.             foreach ($userAddresses as $address) {
  2440.                 if ($address->getIsPrimary()) {
  2441.                     return [
  2442.                         'plz'     => $address->getZip(),
  2443.                         'street'  => $address->getStreet(),
  2444.                         'city'    => $address->getCity(),
  2445.                         'country' => $address->getCountry(),
  2446.                     ];
  2447.                 }
  2448.             }
  2449.             $address $userAddresses->first();
  2450.             return [
  2451.                 'plz'     => $address->getZip(),
  2452.                 'street'  => $address->getStreet(),
  2453.                 'city'    => $address->getCity(),
  2454.                 'country' => $address->getCountry(),
  2455.             ];
  2456.         }
  2457.         return [
  2458.             'plz'     => $user->getZip(),
  2459.             'street'  => $user->getStreet(),
  2460.             'city'    => $user->getCity(),
  2461.             'country' => $user->getCountry(),
  2462.         ];
  2463.     }
  2464.     /**
  2465.      * isValidPricesLimit
  2466.      *
  2467.      * @param  mixed $header_id
  2468.      * @return bool
  2469.      */
  2470.     public function isValidPricesLimit($header_id): bool
  2471.     {
  2472.         $generalLimitCustomer '-1';
  2473.         $entityManager $this->getDoctrine()->getManager();
  2474.         /** @var Setting $general_limit */
  2475.         $general_limit $entityManager->getRepository(Setting::class)->find(20);
  2476.         /** @var WiCamHeader $WiCamHeader */
  2477.         $WiCamHeader $entityManager->getRepository(WiCamHeader::class)->find($header_id);
  2478.         $Customer $WiCamHeader->getCustomer();
  2479.         if(!empty($Customer)){
  2480.             if ($Customer->getLimitPurchase() > 0) {
  2481.                 $generalLimitCustomer $WiCamHeader->getCustomer()->getLimitPurchase();
  2482.             }
  2483.             $totalOrders $entityManager->getRepository(WiCamHeader::class)->getCustomerTotal($Customer);
  2484.             $totalGeneral $WiCamHeader->getGeneralTotal();
  2485.             $finalTotal = (float) $totalOrders $totalGeneral;
  2486.             $limitReached false;
  2487.             if ('-1' != $generalLimitCustomer) {
  2488.                 if ((float)$totalOrders > (float) $generalLimitCustomer) {
  2489.                     $limitReached true;
  2490.                 }
  2491.             } elseif ('0' != $general_limit->getValue()) {
  2492.                 if ((float)$totalOrders > (float) $general_limit->getValue()) {
  2493.                     $limitReached true;
  2494.                 }
  2495.             }
  2496.             return $limitReached;
  2497.         } else {
  2498.             return false;
  2499.         }
  2500.     }
  2501. }