src/Controller/StockController.php line 106

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Attribute;
  4. use App\Entity\Cart;
  5. use App\Entity\Category;
  6. use App\Entity\Color;
  7. use App\Entity\Grade;
  8. use App\Entity\Manufacturer;
  9. use App\Entity\Model;
  10. use App\Entity\Option;
  11. use App\Entity\Order;
  12. use App\Entity\Product;
  13. use App\Entity\Shop;
  14. use App\Entity\Stock;
  15. use App\Form\SavType;
  16. use App\Form\SearchType;
  17. use App\Form\StockType;
  18. use App\Repository\CategoryRepository;
  19. use App\Repository\ManufacturerRepository;
  20. use App\Repository\OptionRepository;
  21. use App\Repository\StockRepository;
  22. use App\Service\HistoryService;
  23. use App\Service\ShopService;
  24. use App\Service\UserService;
  25. use DateTime;
  26. use Doctrine\ORM\EntityManagerInterface;
  27. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  28. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  29. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  30. use Symfony\Component\HttpFoundation\JsonResponse;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use Symfony\Component\HttpFoundation\RequestStack;
  33. use Symfony\Component\HttpFoundation\Response;
  34. use Symfony\Component\HttpKernel\KernelInterface;
  35. use Symfony\Component\Routing\Annotation\Route;
  36. use Symfony\Component\Translation\TranslatableMessage;
  37. use Symfony\Contracts\Translation\TranslatorInterface;
  38. /**
  39.  * @Route("/{_locale<%app.supported_locales%>}/stock")
  40.  */
  41. class StockController extends AbstractController
  42. {
  43.     private $shop_config;
  44.     private $shop_grades;
  45.     private $shop_selling_grades;
  46.     private $attributes = array(
  47.         '0'=>'size',
  48.         '1'=>'storage',
  49.         '2'=> 'memory',
  50.         '3'=> 'screen_size',
  51.         '4'=> 'screen_resolution',
  52.         '5'=> 'connectivity',
  53.         '6'=> 'connectic',
  54.         '7'=> 'width',
  55.         '8'=> 'height',
  56.         '9'=> 'depth',
  57.         '10'=> 'weight',
  58.         '11'=> 'ID_recognition',
  59.         '12'=> 'battery',
  60.         '13'=> 'front_camera',
  61.         '14'=> 'rear_camera',
  62.         '15'=> 'external_storage',
  63.         '16'=> 'SIM',
  64.         '17'=> 'OS',
  65.         '18'=>'usage',
  66.         '19'=> 'format',
  67.         '20'=> 'screen type',
  68.         '21'=> 'touch',
  69.         '22'=> 'webcam',
  70.         '23'=> 'audio',
  71.         '24'=> 'ratio',
  72.         '25'=> 'connectic 2',
  73.         '26'=> 'network card',
  74.         '27'=> 'graphic card',
  75.         '28'=> 'support',
  76.         '29'=> 'keyboard',
  77.         '30'=> 'numeric pad',
  78.         '31'=> 'processor',
  79.         '32'=> 'speed',
  80.         '33'=> 'generation',
  81.         '34'=> 'size',
  82.         '35'=> 'norme support',
  83.     );
  84.     private $cachedPrices=array();
  85.     private $capacities=[ //percents on price
  86.         32=>0,
  87.         64=>25,
  88.         128=>20,
  89.         256=>15,
  90.         512=>12.5,
  91.         1000=>12.5
  92.     ];
  93.     /**
  94.      * @Route("/", name="app_stock_index", methods={"GET"})
  95.      */
  96.     public function index(Request $requestStockRepository $stockRepositoryCategoryRepository $categoryRepositoryManufacturerRepository $manufacturerRepositoryUserService $userServiceRequestStack $requestStackShopService $shopServiceParameterBagInterface $paramsTranslatorInterface $translator): Response
  97.     {
  98.         $session $request->getSession();
  99.         $locale $request->getLocale();
  100.         // echo $locale;
  101.         $template_sub_file '_list';
  102.         $request $requestStack->getCurrentRequest();
  103.         $user $this->getUser();
  104.         if(!$user->getShop()) {
  105.             $userService->setDefaultShop($user);
  106.         }
  107.         if($shop $user->getShop()) {
  108.             $vat $shopService->getSetting($shop'vat');
  109.             if($shopService->getSetting($shop'view-as-card')) {
  110.                 $template_sub_file='_cards';
  111.             }
  112.             /*
  113.             $settings=$shop->getSettings();
  114.             foreach($settings as $shop_setting) {
  115.                 $setting=$shop_setting->getSetting();
  116.                 if($setting->getMachineName()=='view-as-card' && $shop_setting->getValue()==1) {
  117.                     $template_sub_file='_cards';
  118.                 }
  119.                 //echo $shop_setting->getValue();
  120.             }
  121.             //temp
  122.             if($shop->getId()==9) {
  123.                 $template_sub_file = '_cards';
  124.             }
  125.             */
  126.             /*if($shop->getCountry()=='es') {
  127.                 $vat=21;
  128.             }*/
  129.         }
  130.         $cats $stockRepository->findCategoriesByShop($shop);
  131.         foreach($cats as $k=>$st) {
  132.             if(preg_match('/pack/i',$st->getModel()->getCategory()->getName())) {
  133.                 $st->getModel()->getCategory()->setName("Pack/Deal");
  134.             }
  135.             //echo $st->getModel()->getCategory()->getName();
  136.             //echo $cat->getId();
  137.         }
  138.         if($shopService->getSetting($shop'view-as-card')) {
  139.             $categories=array();
  140.             foreach($cats as $stock) {
  141.                 $label=new TranslatableMessage($stock->getModel()->getCategory()->getName());
  142.                 $categories[$stock->getModel()->getCategory()->getId()]= $label;
  143.             }
  144.             //$categories = array_merge(array_flip(array('MOBILE', 'TABLET', 'LAPTOP','DESKTOP','SCREEN','PACK','ROUTER','TV')), $categories);
  145.             $order=array('1''2''3','6','7','12','19','17','13');
  146.             uksort($categories, function($key1$key2) use ($order) {
  147.                 return (array_search($key1$order) > array_search($key2$order));
  148.             });
  149.         }
  150.         $stocks $stockRepository->findByShop($shop$request);
  151.         foreach($stocks as $s) {
  152.             $request->getSession()->remove('stock_'.$s->getId());
  153.         }
  154.         $list=$this->list($stocks$manufacturerRepository);
  155.         $currentCategory=null;
  156.         if($category $request->query->get('category')) {
  157.             $currentCategory=$categoryRepository->find($category);
  158.         }
  159.         return $this->render('stock/index.html.twig', [
  160.             'template_sub_file'=>$template_sub_file,
  161.             'stocks' => $list['stocks'],
  162.             'manufacturers' => $list['manufacturers'],
  163.             'models' => $list['models'],
  164.             'colors' => $list['colors'],
  165.             'grades' => $list['grades'],
  166.             'categories' => isset($categories)?$categories:$list['categories'],
  167.             'currentCategory' => $currentCategory,
  168.             //'title'=>$translator->trans(ucfirst(strtolower($currentCategory->getName()))),
  169.             'shops' => $list['shops'],
  170.             'cats'=>$cats,
  171.             'vat'=>$vat,
  172.             'config'=>$shop?$shop->getConfig():null
  173.         ]);
  174.     }
  175.     /**
  176.      * @Route("/{id}/card", name="app_stock_card", methods={"POST"})
  177.      */
  178.     public function card(Stock $stockRequest $request, ): Response
  179.     {
  180.         return $this->render('stock/_card.html.twig', [
  181.             'stock'=>$stock,
  182.             'ajax'=>true
  183.             ]);
  184.     }
  185.     public function list($stocks,  ManufacturerRepository $manufacturerRepository):array {
  186.         $manufacturers = array();
  187.         $models = array();
  188.         $colors = array();
  189.         $grades = array();
  190.         $categories = array();
  191.         $shops = array();
  192.         foreach ($stocks as $stock) {
  193.             //$product = $stock->getProduct();
  194.             if (!isset($colors[$stock->getColor()->getId()])) {
  195.                 $colors[$stock->getColor()->getId()] = $stock->getColor()->getName();
  196.             }
  197.             if (!isset($manufacturers[$stock->getModel()->getManufacturer()->getId()])) {
  198.                 $manufacturerId=$stock->getModel()->getManufacturer()->getId();
  199.                 $manufacturerName=$stock->getModel()->getManufacturer()->getName();
  200.                 if($manufacturerName=="GENERIC") {
  201.                     $t=explode(' ',$stock->getModel()->getName());
  202.                     $manufacturerName=$t[0];
  203.                     if($manufacturer=$manufacturerRepository->findOneBy(['name'=>$t[0]])) {
  204.                         $manufacturerId=$manufacturer->getId();
  205.                     }
  206.                 }
  207.                 $manufacturers[$manufacturerId] = $manufacturerName;
  208.             }
  209.             if (!isset($models[$stock->getModel()->getId()])) {
  210.                 $models[$stock->getModel()->getId()] = $stock->getModel()->getName();
  211.             }
  212.             if (!isset($grades[$stock->getGrade()])) {
  213.                 $grades[$stock->getGrade()] = $stock->getGrade();
  214.             }
  215.             if (!isset($categories[$stock->getModel()->getCategory()->getId()])) {
  216.                 $categories[$stock->getModel()->getCategory()->getId()] = $stock->getModel()->getCategory()->getName();
  217.             }
  218.             if (!isset($shops[$stock->getShop()->getId()])) {
  219.                 $shops[$stock->getShop()->getId()] = $stock->getShop()->getName();
  220.             }
  221.             if($stock->getQty()==-1) {
  222.                 //$stock->setQty(1);
  223.             }
  224.         }
  225.         asort($manufacturers);
  226.         asort($models);
  227.         asort($colors);
  228.         asort($grades);
  229.         asort($categories);
  230.         asort($shops);
  231.         return array(
  232.             'stocks' => $stocks,
  233.             'manufacturers' => $manufacturers,
  234.             'models' => $models,
  235.             'colors' => $colors,
  236.             'grades' => $grades,
  237.             'categories' => $categories,
  238.             'shops' => $shops
  239.         );
  240.     }
  241.     /**
  242.      * @Route("/admin", name="app_stock_admin_list", methods={"GET"})
  243.      */
  244.     public function admin(StockRepository $stockRepositoryRequest $request): Response
  245.     {
  246.         $stocks=$stockRepository->findBy(['shop'=>$request->query->get('shop')]);
  247.         return $this->render('stock/index_admin.html.twig', [
  248.             'stocks' => $stocks,
  249.         ]);
  250.     }
  251.     /**
  252.      * @Route("/{id}", name="app_stock_show", methods={"GET"})
  253.      */
  254.     public function show(Stock $stock): Response
  255.     {
  256.         return $this->render('stock/show.html.twig', [
  257.             'stock' => $stock,
  258.         ]);
  259.     }
  260.     /**
  261.      * @Route("/{id}/edit", name="app_stock_edit", methods={"GET","POST"})
  262.      */
  263.     public function edit(Stock $stockEntityManagerInterface $entityManagerRequest $request,): Response
  264.     {
  265.         $form $this->createForm(StockType::class, $stock);
  266.         $form->handleRequest($request);
  267.         if ($form->isSubmitted() && $form->isValid()) {
  268.             $entityManager->flush();
  269.         }
  270.         return $this->renderForm('stock/edit.html.twig', [
  271.             'stock' => $stock,
  272.             'form' => $form,
  273.         ]);
  274.     }
  275.     /**
  276.      * @Route("/option", name="app_stock_option_price", methods={"POST","GET"})
  277.      */
  278.     public function optionalPrice(Request $request): Response
  279.     {
  280.         $em $this->getDoctrine()->getManager();
  281.         $price=0;
  282.         if($stock=$em->getRepository(Stock::class)->find($request->request->get('stock'))) {
  283.             $price=$stock->getPrice();
  284.             if($option=$em->getRepository(Option::class)->find($request->request->get('option'))) {
  285.                 //if($stock->getModel()->getCategory()->hasOption($option)) {
  286.                 if(str_contains($option->getPrice(), '%')) {
  287.                     //percent
  288.                     $price=$stock->getPrice()+(((int)$option->getPrice()*$stock->getPrice())/100);
  289.                     //}
  290.                 }
  291.                 else {
  292.                     $price=$stock->getPrice()+$option->getPrice();
  293.                 }
  294.             }
  295.         }
  296.         return new JsonResponse(array(
  297.             'price'=>$price
  298.         ));
  299.     }
  300.     public function import($em$bak2_api_urlHistoryService $historyService$shopId=null)
  301.     {
  302.         $lastUpdate=new DateTime('now');
  303.         $this->em $em;
  304.         if($shopId) {
  305.             $shops = [$em->getRepository(Shop::class)->find($shopId)];
  306.         } else {
  307.             $shops $em->getRepository(Shop::class)->findBy(['active'=>1]);
  308.         }
  309.         $destock=$this->getCurrentDestock();
  310.         $em->getRepository(Product::class)->reset();
  311.         foreach ($shops as $shop) {
  312.             //$em->getRepository(Stock::class)->reset($shop);
  313.         }
  314.         foreach ($shops as $shop) {
  315.             $this->cachedPrices=array();
  316.             /*if($shop->getId()==9) { // AFPA pas de màj
  317.                 continue;
  318.             }*/
  319.             $shopHasOption=false;
  320.             $shopHasCategory=false;
  321.             echo "######## ".$shop->getWttName() . " #############\n";
  322.             //$em->getRepository(Stock::class)->reset($shop);
  323.             $stockData null;
  324.             $this->shop_config null;
  325.             $this->shop_grades null;
  326.             $this->shop_selling_grades null;
  327.             $options=$shop->getOptions();
  328.             if(count($options)>0) {
  329.                 $shopHasOption=true;
  330.             }
  331.             $shopCat=$shop->getCategories();
  332.             $shopCategories=[];
  333.             if(count($shopCat)>0) {
  334.                 $shopHasCategory=true;
  335.                 foreach($shopCat as $k=>$cat) {
  336.                     $shopCategories[$cat->getWttId()]=$cat->getWttId();
  337.                 }
  338.             }
  339.             echo "######## has options: ".$shopHasOption " #############\n";
  340.             echo "######## has categories: ".$shopHasCategory " ##".implode(',',$shopCategories)."###########\n";
  341.             $configContent file_get_contents($bak2_api_url "/tempStock.php?action=config&channel=" $shop->getWttName());
  342.             $configData json_decode($configContent);
  343.             $this->shop_config reset($configData);
  344.             $vboxIds $this->shop_config->vbox;
  345.             $shop->setConfig($configData);
  346.             $em->persist($shop);
  347.             $em->flush();
  348.             $allGrades $em->getRepository(Grade::class)->findAll();
  349.             if (isset($this->shop_config->grades)) {
  350.                 foreach ($this->shop_config->grades as $from => $to) {
  351.                     //echo $from . " / " . $to . "\n";
  352.                     $this->shop_grades[$from] = $this->em->getRepository(Grade::class)->findOneByName($to);
  353.                 }
  354.             } else {
  355.                 $allGrades $em->getRepository(Grade::class)->findAll();
  356.                 foreach ($allGrades as $grade) {
  357.                     $this->shop_grades[$grade->getName()] = $grade;
  358.                 }
  359.             }
  360.             if (isset($this->shop_config->quality)) {
  361.                 foreach ($this->shop_config->quality as $quality) {
  362.                     $this->shop_selling_grades[$quality->outGrade] = $quality->quality;
  363.                 }
  364.             } else {
  365.                 if (isset($this->shop_config->grades)) {
  366.                     foreach ($this->shop_config->grades as $from => $to) {
  367.                         //echo $from . " / " . $to . "\n";
  368.                         $this->shop_selling_grades[$from] = $to;
  369.                     }
  370.                 } else {
  371.                     foreach ($allGrades as $grade) {
  372.                         $this->shop_selling_grades[$grade->getName()] = $grade->getName();
  373.                     }
  374.                 }
  375.             }
  376.             // var_dump($this->shop_selling_grades);
  377.             if(count($this->shop_selling_grades)==1) {
  378.                 $outGrade  array_key_first($this->shop_selling_grades);
  379.             }
  380.             $importUrl $bak2_api_url "/tempStock.php?action=getProductByTempVbox&vboxes=" $vboxIds "&sku_marketplace=".($shop->getId()==5?'b2c':'b2b')."&marketplaceId=" $shop->getWttId();
  381.             echo $importUrl."\n";
  382.             $importUrl=preg_replace('/ /','',$importUrl);
  383.             $stockContent file_get_contents($importUrl);
  384.             $stockData json_decode($stockContent);
  385.             $disableModels=array();
  386.             $existingStock=$em->getRepository(Stock::class)->findBy(array('shop'=>$shop->getId()));
  387.             foreach($existingStock as $stock) {
  388.                 $disableModels[$stock->getModel()->getWttId()]=$stock->getModel();
  389.             }
  390.             foreach ($stockData as $k => $stockProduct) {
  391.                 if(!is_object($stockProduct)) {
  392.                     continue;
  393.                 }
  394.                 if (!isset($stockProduct->colorId) || $stockProduct->colorId == 0) {
  395.                     $stockProduct->colorId 99;
  396.                     $stockProduct->color "UNKNOWN";
  397.                 }
  398.                 if (!isset($outGrade) && !isset($this->shop_selling_grades[$stockProduct->outGrade]) && $stockProduct->outGrade!='unknown') {
  399.                     //var_dump($this->shop_selling_grades);
  400.                     //echo " ----->" . $stockProduct->outGrade . " (" . $stockProduct->outGradeId . ") not allowed \n";
  401.                     unset($stockData[$k]);
  402.                 }
  403.             }
  404.             foreach ($stockData as $stockProduct) {
  405.                 if(!is_object($stockProduct)) {
  406.                     continue;
  407.                 }
  408.                 if($shopHasCategory) {
  409.                     if(!in_array($stockProduct->categoryId$shopCategories)) {
  410.                         continue;
  411.                     }
  412.                 }
  413.                 echo "----" $stockProduct->model "-(".$stockProduct->modelId.")---\n";
  414.                 unset($disableModels[$stockProduct->modelId]);
  415.                 if (!$stockProduct->modelId) {
  416.                     echo "No modelId : ".$stockProduct->model." / ".$stockProduct->manufacturer." / ".$stockProduct->color." / ".$stockProduct->outGrade."\n";
  417.                     //var_dump($stockProduct);
  418.                     continue;
  419.                 }
  420.                 if (!$stockProduct->sku) {
  421.                     if($this->shop_config->sourceable==1) {
  422.                         $stockProduct->sku="W-".$stockProduct->modelId."-".$stockProduct->colorId."-".$stockProduct->outGradeId;
  423.                         //$skucontent = file_get_contents($bak2_api_url . "/sku.php?sku=".$sku."&modelId=".$stockProduct->modelId."&outGradeId=".$stockProduct->outGradeId."&colorId=".$stockProduct->colorId."&channel=b2b");
  424.                     }
  425.                     else {
  426.                         echo "No sku : ".$stockProduct->model." / ".$stockProduct->manufacturer." / ".$stockProduct->color." / ".$stockProduct->outGrade."\n";
  427.                         continue;
  428.                     }
  429.                 }
  430.                 if ($stockProduct->colorId == 0) {
  431.                     $stockProduct->colorId 99;
  432.                     $stockProduct->color "UNKNOWN";
  433.                 }
  434.                 if(!isset($destock[$stockProduct->sku])) {
  435.                     $destock[$stockProduct->sku]=0;
  436.                 }
  437.                 $stockProduct->nb=$stockProduct->nb-$destock[$stockProduct->sku];
  438.                 if(!isset($outGrade)) {
  439.                     if (!$grade $em->getRepository(Grade::class)->findOneBy(array('wttId' => $stockProduct->outGradeId))) {
  440.                         $grade = new Grade();
  441.                         $grade->setName($stockProduct->outGrade);
  442.                         $grade->setWttId($stockProduct->outGradeId);
  443.                         $em->persist($grade);
  444.                         $em->flush();
  445.                     }
  446.                 }
  447.                 else {
  448.                     $grade $em->getRepository(Grade::class)->findOneBy(array('name' => $outGrade));
  449.                 }
  450.                 //echo "Original grade:" . $grade->getName() . "\n";
  451.                 // var_dump($this->shop_grades);
  452.                 if(!isset($this->shop_grades[$grade->getName()])) {
  453.                     echo "Unknown grade: ".$grade->getName()."\n";
  454.                     continue;
  455.                     //var_dump($this->shop_grades);
  456.                 }
  457.                 else {
  458.                     $shopGrade $this->shop_grades[$grade->getName()];
  459.                 }
  460.                 //echo "Shop grade: " . $shopGrade->getName() . "\n";
  461.                 //echo "Selling grade: " . $this->shop_selling_grades[$shopGrade->getName()] . "\n";
  462.                 //echo $stockProduct->modelId . "\n";
  463.                 //echo $stockProduct->colorId . "\n";
  464.                 if (!$color $em->getRepository(Color::class)->findOneBy(array('wttId' => $stockProduct->colorId))) {
  465.                     $color = new Color();
  466.                     $color->setName($stockProduct->color);
  467.                     $color->setWttId($stockProduct->colorId);
  468.                     $em->persist($color);
  469.                     $em->flush();
  470.                 }
  471.                 //echo $color->getName() . "\n";
  472.                 if (!$category $em->getRepository(Category::class)->findOneBy(array('wttId' => $stockProduct->categoryId))) {
  473.                     $category = new Category();
  474.                     $category->setName($stockProduct->categoryName);
  475.                     $category->setWttId($stockProduct->categoryId);
  476.                     $category->setType('Model');
  477.                     $em->persist($category);
  478.                     $em->flush();
  479.                 }
  480.                 if (!$stockProduct->manufacturer) {
  481.                     $stockProduct->manufacturer "UNKNOWN";
  482.                 }
  483.                 if(!$manufacturer $em->getRepository(Manufacturer::class)->findOneBy(array('name' => $stockProduct->manufacturer))) {
  484.                     $manufacturer = new Manufacturer();
  485.                     $manufacturer->setName($stockProduct->manufacturer);
  486.                     //$manufacturer->setWttId($stockProduct->manufacturerId);
  487.                     $em->persist($manufacturer);
  488.                     $em->flush();
  489.                 }
  490.                 if (!$model $em->getRepository(Model::class)->findOneBy(array('wttId' => $stockProduct->modelId))) {
  491.                     // var_dump($stockProduct);
  492.                     $model = new Model();
  493.                     $model->setName($stockProduct->model);
  494.                     $model->setWttId($stockProduct->modelId);
  495.                     $model->setManufacturer($manufacturer);
  496.                     $model->setCategory($category);
  497.                     $em->persist($model);
  498.                     $em->flush();
  499.                 }
  500.                 if (isset($stockProduct->attr_id) && isset($stockProduct->attr_val)) {
  501.                     $tId=explode('|',$stockProduct->attr_id);
  502.                     $tVal=explode('|',$stockProduct->attr_val);
  503.                     $tName=explode('|',$stockProduct->attr_name);
  504.                     foreach($tId as $k=>$v) {
  505.                         $attributeId=(int)$tId[$k];
  506.                         //$attributeName=$tName[$k];
  507.                         $attributeValue=$tVal[$k];
  508.                         if(($model->getCategory()->getId()==|| $model->getCategory()->getId()==2) && $attributeId==&& $capacities=explode('/'$attributeValue)) {
  509.                             $attributePrice=0;
  510.                             foreach($capacities as $k2=>$capacity) {
  511.                                 $capacity=(int)$capacity;
  512.                                 if($capacity<4) {
  513.                                     $capacity=1000*$capacity;
  514.                                 }
  515.                                 if($k2==0) {
  516.                                     $attributePrice=0;
  517.                                 }
  518.                                 $capacityName=$capacity<1000?($capacity." GB"):(($capacity/1000)." TB");
  519.                                 if($k2>0) {
  520.                                     $attributePrice=$attributePrice+$this->capacities[$capacity];
  521.                                 }
  522.                                 echo "k2 ".$k2." - attributePrice: ".$attributePrice."\n";
  523.                                 if (!$attribute $em->getRepository(Attribute::class)->findOneBy(array('model' => $model->getId(),'wttId'=>$attributeId,'name'=>$this->attributes[$attributeId],'value'=>$capacityName))) {
  524.                                     $attribute=new Attribute();
  525.                                     $attribute->setModel($model);
  526.                                     $attribute->setName($this->attributes[$attributeId]);
  527.                                     $attribute->setWttId($attributeId);
  528.                                     $attribute->setValue($capacityName);
  529.                                     //$attribute->setPrice($attributePrice);
  530.                                     $em->persist($attribute);
  531.                                 }
  532.                                 $attribute->setPrice($attributePrice);
  533.                                 $em->persist($attribute);
  534.                             }
  535.                             //die();
  536.                         }
  537.                         else {
  538.                             if($attributeValue!='' && $attributeId>0) {
  539.                                 if (!$attribute $em->getRepository(Attribute::class)->findOneBy(array('model' => $model->getId(),'wttId'=>$attributeId))) {
  540.                                     $attribute=new Attribute();
  541.                                     $attribute->setModel($model);
  542.                                     //$attribute->setName($this->attributes[$attributeId]);
  543.                                     $attribute->setWttId($attributeId);
  544.                                     //$attribute->setValue($attributeValue);
  545.                                     $em->persist($attribute);
  546.                                 }
  547.                                 $attribute->setName($this->attributes[$attributeId]);
  548.                                 $attribute->setValue($attributeValue);
  549.                                 $em->persist($attribute);
  550.                             }
  551.                         }
  552.                     }
  553.                 }
  554.                 if(isset($stockProduct->pict) ) {
  555.                     echo $stockProduct->pict."\n";
  556.                     if(!$model->getImage() || str_contains($model->getImage(), 'http')) {
  557.                         echo "update pict\n";
  558.                         $model->setImage("http://pict.bak2group.com/models/".$stockProduct->pict);
  559.                         $em->persist($model);
  560.                         $em->flush();
  561.                     }
  562.                 }
  563.                 /*
  564.                 $model->setCategory($category);
  565.                 $em->persist($model);
  566.                 $em->flush();
  567.                 */
  568.                 //echo $model->getName() . "\n";
  569.                 $productGrade $grade->getName();
  570.                 //echo $category->getName()."\n";
  571.                 if (!$product $em->getRepository(Product::class)->findOneBy(array('model' => $model'color' => $color'grade' => $grade'sku' => $stockProduct->sku))) {
  572.                     $product = new Product();
  573.                     $product->setColor($color);
  574.                     $product->setModel($model);
  575.                     $product->setGrade($grade);
  576.                     $product->setSku($stockProduct->sku);
  577.                     $product->setQty($stockProduct->nb);
  578.                     $product->setName($manufacturer->getName() . " " $model->getName() . " " $color->getName() . " " $grade->getName());
  579.                     $product->setPrice($stockProduct->$productGrade);
  580.                     $product->setChannel($shop->getChannel());
  581.                     $em->persist($product);
  582.                     $em->flush();
  583.                 }
  584.                 $product->setChannel($shop->getChannel());
  585.                 //$product->setCategory($category);
  586.                 if($product->getQty()<=0) {
  587.                     $product->setQty($stockProduct->nb);
  588.                     $product->setPrice($stockProduct->$productGrade);
  589.                     //$product->setName($manufacturer->getName()." ".$model->getName()." ".$color->getName()." ".$grade->getName());
  590.                     $em->persist($product);
  591.                     $em->flush();
  592.                     echo "updating ".$product->getName()."\n";
  593.                 }
  594.                 if($product->getSku()=='n.a.') {
  595.                     $product->setSku($stockProduct->sku);
  596.                     $em->persist($product);
  597.                     $em->flush();
  598.                 }
  599.                 // echo $product->getName() . "\n";
  600.                 if(!isset($this->shop_selling_grades[$grade->getName()])) {
  601.                     continue;
  602.                 }
  603.                 if (!$stock $em->getRepository(Stock::class)->findOneBy(array('shop' => $shop'model' => $model'color' => $color'grade' => $this->shop_selling_grades[$grade->getName()]))) {
  604.                     $stock = new Stock();
  605.                     //echo "sku:" . $stockProduct->sku . "\n";
  606.                     $stock->setModel($model);
  607.                     $stock->setGrade($this->shop_selling_grades[$grade->getName()]);
  608.                     $stock->setColor($color);
  609.                     $stock->setShop($shop);
  610.                     $stock->setQty(0);
  611.                     $stock->setSourceGrade($stockProduct->outGrade);
  612.                     $em->persist($stock);
  613.                     echo "-------------> create model: " $stockProduct->modelId "  -- Shop grade: " $shopGrade->getName() . " -- Color: " $stockProduct->colorId " (" $stockProduct->outGrade ")\n";
  614.                 }
  615.                 $overridenPrice=$stock->getPrice();
  616.                 echo "shop:".$shop->getName()." model: " $stockProduct->modelId "  -- Shop grade: " $shopGrade->getName() . " -- Color: " $stockProduct->colorId " (" $stockProduct->outGrade ")\n";
  617.                 echo "qty 1: ".$stock->getQty()."\n";
  618.                 if($stock->getQty()<2) {
  619.                     $stock->setQty(0);
  620.                 }
  621.                 $shopGrade $shopGrade->getName();
  622.                 $price $this->getPriceNet($stockProduct->$shopGrade 100$shop$bak2_api_url);
  623.                 $sourceGrade=explode(',',$stock->getSourceGrade());
  624.                 $sourceGrade[]=$stockProduct->outGrade;
  625.                 $stock->setSourceGrade(implode(',',array_filter(array_unique($sourceGrade))));
  626.                 $stock->setPrice((int)$price 100);
  627.                 $stock->setEnabled(true);
  628.                 //$stock->setQty($stock->getQty() + $stockProduct->nb);
  629.                 $stock->setQty($stockProduct->nb);
  630.                 echo "qty: ".$stock->getQty()."\n";
  631.                 //options
  632.                 echo "Options \n";
  633.                 if($shopHasOption) {
  634.                     foreach($stock->getOptions() as $option) {
  635.                         $stock->removeOption($option);
  636.                     }
  637.                      if(count($options)>0) {
  638.                          echo "Has options \n";
  639.                             $modelAttributes=$stock->getModel()->getAttributes();
  640.                             $t=array();
  641.                             foreach($modelAttributes as $attribute) {
  642.                                 if($attribute->getName()=='storage' || $attribute->getName()=='memory') {
  643.                                     $t[$attribute->getName()]=(int)$attribute->getValue();
  644.                                 }
  645.                             }
  646.                             $modelAttributes=$t;
  647.                             foreach($shop->getOptions() as $option) {
  648.                                // if($option->getCategory()->getId()==$stock->getModel()->getCategory()->getId()) {
  649.                                 if($optionAttribute $option->getAttribute()) {
  650.                                     if(isset($modelAttributes[$option->getAttribute()->getName()])) {
  651.                                         if((int)$modelAttributes[$option->getAttribute()->getName()]==(int)$option->getAttributeValue()) {
  652.                                             if($option->getCategory()->getId()==$stock->getModel()->getCategory()->getId()) {
  653.                                                 $stock->addOption($option);
  654.                                             }
  655.                                         }
  656.                                     }
  657.                                 }
  658.                                 else {
  659.                                     if($option->getCategory()) {
  660.                                         if($option->getCategory()->getId()==$stock->getModel()->getCategory()->getId()) {
  661.                                             $stock->addOption($option);
  662.                                         }
  663.                                     }
  664.                                 }
  665.                             }
  666.                             //die();
  667.                         }
  668.                 }
  669.                 else {
  670.                     foreach($stock->getOptions() as $option) {
  671.                         $stock->removeOption($option);
  672.                     }
  673.                 }
  674.                 $stock->setUpdated($lastUpdate);
  675.                 if($stock->isOverride()) {
  676.                     $stock->setPrice($overridenPrice);
  677.                     echo "### stock overriden, continue\n";
  678.                     //die();
  679.                     continue;
  680.                 }
  681.                 $em->persist($stock);
  682.                 echo "Stock saved\n";
  683.                 if($stock->getId()) {
  684.                     if(!$historyService->getHistory('stock'$stock->getId(),'status','created')) {
  685.                         $historyService->setHistory('stock',$stock->getId(),'status','created');
  686.                         $historyService->setHistory('stock',$stock->getId(), 'status''updated');
  687.                         $historyService->setHistory('stock',$stock->getId(), 'price',  $stock->getPrice());
  688.                         // $historyService->setHistory('stock',$stock->getId(),'updated');
  689.                     }
  690.                     if($historyService->getHistory('stock'$stock->getId(),'price')!=$stock->getPrice()) {
  691.                         $historyService->setHistory('stock',$stock->getId(), 'price',  $stock->getPrice());
  692.                         $historyService->setHistory('stock',$stock->getId(), 'status''updated');
  693.                     }
  694.                     echo "History done\n";
  695.                 }
  696.             }
  697.             foreach($disableModels as $k=>$model) {
  698.                 $existingStock=$em->getRepository(Stock::class)->findBy(array('shop'=>$shop->getId(),'model'=>$model));
  699.                 $stock=$existingStock[0];
  700.                 $stock->setEnabled(false);
  701.                 echo "remove ".$model."\n";
  702.                 $stock->setQty(0);
  703.             }
  704.             // var_dump($disableModels);
  705.             $em->flush();
  706.         }
  707.         //var_dump($this->cachedPrices);
  708.         return new Response('ok');
  709.     }
  710.     public function getPriceNet($price$shop$bak2_api_url)
  711.     {
  712.         if($price<=0) {
  713.             return 0;
  714.         }
  715.         echo "price: ".$price" / MP: ".$shop->getWttId()."\n";
  716.         //$url=https://share.ddev.site:8443/routine/report/api/tempStock.php?action=getBestPrice&marketplaceId=17&price=".$price;
  717.         if(!isset($this->cachedPrices[$price])) {
  718.             echo "----prices doesn't exist\n";
  719.             $importUrl $bak2_api_url "/tempStock.php?action=getBestPrice&marketplaceId=" $shop->getWttId()."&price=".$price;
  720.             echo $importUrl."\n";
  721.             $importUrl=preg_replace('/ /','',$importUrl);
  722.             $stockContent file_get_contents($importUrl);
  723.             $stockData json_decode($stockContent);
  724.             echo "new price ".$stockData->bsp."\n";
  725.             $this->cachedPrices[$price]=$stockData->bsp;
  726.         }
  727.         else {
  728.             echo "----ok prices cached\n";
  729.         }
  730.         return $this->cachedPrices[$price];
  731.         /*
  732.         if($price<=0) {
  733.             return 0;
  734.         }
  735.         $internalCost = (float)$this->shop_config->internalCost;
  736.         $labor = (float)$this->shop_config->laborCost;
  737.         $logistic = (float)$this->shop_config->logisticCost;
  738.         $accessory = (float)$this->shop_config->accessoryCost;
  739.         $warranty_percentage = (float)$this->shop_config->warranty_perentage;
  740.         $warranty_fixe = (float)$this->shop_config->warranty_fixe;
  741.         $commision_percentage = (float)$this->shop_config->commision_perentage;
  742.         $margin_other_percentage = (float)$this->shop_config->margin_other_percentage;
  743.         $margin_tablet_percentage = (float)$this->shop_config->margin_tablet_percentage;
  744.         $tva = (100 + (float)$this->shop_config->tva_percentage) / 100;
  745.         echo "price:" . $price . "\n";
  746.         $bbNet1 = $price / $tva;
  747.         echo "bbNet1: " . $bbNet1 . "\n";
  748.         $bbNet2 = $bbNet1 - ($commision_percentage / 100 * $price);
  749.         echo "bbNet2:" . $bbNet2 . "\n";
  750.         $bbNet3 = $bbNet2 - ($warranty_percentage / 100 * $bbNet2) - $warranty_fixe;
  751.         echo "bbNet3:" . $bbNet3 . "\n";
  752.         $bbNet = $bbNet3 - ($internalCost + $labor + $logistic + $accessory);
  753.         echo $bbNet."\n";
  754.         echo $internalCost ." + ".$labor ." + ". $logistic ." + ". $accessory."\n";
  755.         //Version Nico
  756.         //$pp = ($warranty_perentage/100) + ($commision_perentage/100);
  757.         //$bbNet = (($price-($tva*$warranty_fixe))/($tva*(1+$pp))) - $labor - $logistic - $accessory;
  758.         $bsp1 = $price + $labor + $logistic + $accessory ;
  759.         if($category->getId()==2) {
  760.             //    $bsp1=$bsp1+ $margin_tablet_percentage;
  761.         }
  762.         else {
  763.             //    $bsp1=$bsp1+ $margin_other_percentage;
  764.         }
  765.         echo "bsp1:" . $bsp1 . "\n";
  766.         $bsp2 = $bsp1 + ($warranty_percentage / 100 * $bsp1) + $warranty_fixe;
  767.         echo "bsp2:" . $bsp2 . "\n";
  768.         $bsp = ($bsp2 + ($commision_percentage / 100 * $bsp2)) * $tva;
  769.         echo "bsp:" . $bsp . "\n";
  770.         return $bsp;
  771.         */
  772.     }
  773.     private function getResalePrice($price)
  774.     {
  775.         if($price<=0) {
  776.             return 0;
  777.         }
  778.         if ($price 300) {
  779.             $resalePrice $price 15;
  780.         } elseif ($price 100) {
  781.             $resalePrice $price 10;
  782.         } elseif ($price 50) {
  783.             $resalePrice $price 5;
  784.         } else {
  785.             $resalePrice floor($price 1.08);
  786.         }
  787.         return $resalePrice;
  788.     }
  789.     function getMinPrice($price$grade)
  790.     {
  791.         if ($price 0) {
  792.             if ($price && $grade == 'C') {
  793.                 $price 5;
  794.             } elseif ($price && $grade == 'E') {
  795.                 $price 4;
  796.             } elseif ($price 3) {
  797.                 $price 3;
  798.             }
  799.         }
  800.         return $price;
  801.     }
  802.     private function getCurrentDestock() {
  803.         $destock=array();
  804.         $em=$this->em;
  805.         if($orders$em->getRepository(Order::class)->findBy(array('status'=>10))) {
  806.             $gradeRepository=$em->getRepository(Grade::class);
  807.             $productRepository=$em->getRepository(Product::class);
  808.             $cartRepository=$em->getRepository(Cart::class);
  809.             foreach($orders as $order) {
  810.                 foreach($order->getCarts() as $cart) {
  811.                     $stock=$cart->getStock();
  812.                     $sourceGrades $stock->getSourceGrade();
  813.                     foreach (explode(','$sourceGrades) as $sourceGrade) {
  814.                         if ($grade $gradeRepository->findOneByName($sourceGrade)) {
  815.                             if ($product $productRepository->findOneBy(array('grade' => $grade'model' => $stock->getModel(), 'color' => $stock->getColor()))) {
  816.                                 if(!isset($destock[$product->getSku()])) {
  817.                                     $destock[$product->getSku()]=0;
  818.                                 }
  819.                                 $destock[$product->getSku()] = $destock[$product->getSku()]+$cart->getQty();
  820.                                 break;
  821.                             }
  822.                         }
  823.                     }
  824.                 }
  825.             }
  826.         }
  827.         return $destock;
  828.     }
  829.     public function searchForm() {
  830.         $form =   $this->createForm(SearchType::class);
  831.         return $this->render('stock/search.html.twig', [
  832.             'form' => $form->createView()
  833.         ]);
  834.     }
  835.     public function getHeader(ParameterBagInterface $params) {
  836.         $user=$this->getUser();
  837.         $template_sub_file="stock/header.html.twig";
  838.         if(file_exists($params->get('kernel.project_dir')."/private/shops/".$user->getShop()->getId()."/templates/stock/header.html.twig")) {
  839.             $template_sub_file="shops/".$user->getShop()->getId()."/templates/stock/header.html.twig";
  840.         }
  841.         return $this->render($template_sub_file);
  842.     }
  843.     public function getFooter(ParameterBagInterface $params) {
  844.         $user=$this->getUser();
  845.         $template_sub_file="stock/footer.html.twig";
  846.         if(file_exists($params->get('kernel.project_dir')."/private/shops/".$user->getShop()->getId()."/templates/stock/footer.html.twig")) {
  847.             $template_sub_file="shops/".$user->getShop()->getId()."/templates/stock/footer.html.twig";
  848.         }
  849.         return $this->render($template_sub_file);
  850.     }
  851. }