custom/plugins/NrbnImportCsv/src/Storefront/Controller/ImportCsvController.php line 83

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace NrbnImportCsv\Storefront\Controller;
  3. use Exception;
  4. use Shopware\Core\Checkout\Cart\Cart;
  5. use Shopware\Core\Checkout\Cart\LineItem\LineItem;
  6. use Shopware\Core\Checkout\Cart\LineItemFactoryRegistry;
  7. use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
  8. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  11. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  12. use Shopware\Storefront\Controller\StorefrontController;
  13. use Shopware\Core\Framework\Routing\Annotation\RouteScope;
  14. use Shopware\Storefront\Page\Account\Overview\AccountOverviewPageLoader;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. /**
  19.  * @RouteScope(scopes={"storefront"})
  20.  */
  21. class ImportCsvController extends StorefrontController
  22. {
  23.     /**
  24.      * @var LineItemFactoryRegistry
  25.      */
  26.     private LineItemFactoryRegistry $factory;
  27.     /**
  28.      * @var EntityRepositoryInterface
  29.      */
  30.     private EntityRepositoryInterface $productRepository;
  31.     /**
  32.      * @var CartService
  33.      */
  34.     private CartService $cartService;
  35.     /**
  36.      * @var AccountOverviewPageLoader
  37.      */
  38.     private AccountOverviewPageLoader $overviewPageLoader;
  39.     /**
  40.      * @var string
  41.      */
  42.     private string $productErr "";
  43.     public function __construct(
  44.         LineItemFactoryRegistry   $factory,
  45.         CartService               $cartService,
  46.         EntityRepositoryInterface $productRepository,
  47.         AccountOverviewPageLoader $overviewPageLoader
  48.     ){
  49.         $this->factory            $factory;
  50.         $this->cartService        $cartService;
  51.         $this->productRepository  $productRepository;
  52.         $this->overviewPageLoader $overviewPageLoader;
  53.     }
  54.     /**
  55.      * @Route("/account/importcsv", name="frontend.netz_reform_import_csv.upload", methods={"GET", "POST"})
  56.      * @return Response
  57.      */
  58.     public function upload(Request $requestSalesChannelContext $context) : Response
  59.     {
  60.         $submitBtn $request->request->get("submit");
  61.         if($submitBtn) {
  62.             $file $request->files->get("upload_file");
  63.             if(
  64.                 $file &&
  65.                 ($file->getMimeType() === 'text/csv' || $file->getMimeType() === "text/plain")
  66.             ){
  67.                 $this->importFile($file$context);
  68.                 return $this->redirectToRoute("frontend.checkout.cart.page");
  69.             }
  70.         }
  71.         $page $this->overviewPageLoader->load($request$context$context->getCustomer());
  72.         return $this->renderStorefront("@NrbnImportCsv/storefront/page/import.html.twig",
  73.             ['error'=>$this->productErr,'page'=>$page]
  74.         );
  75.     }
  76.     /**
  77.      * @Route("/account/exportcsv",name="frontend.netz_reform_import_csv.export", methods={"GET"})
  78.      * @param Cart $cart
  79.      * @param SalesChannelContext $context
  80.      * @return void
  81.      */
  82.     public function exportFile(Cart $cartSalesChannelContext $context) {
  83.         if($cart){
  84.             $file fopen("php://output""w");
  85.             header('Content-Type: application/csv');
  86.             header('Content-Disposition: attachment; filename=cart.csv;');
  87.             $lineItems $cart->getLineItems();
  88.             foreach ($lineItems as $lineItem){
  89.                 $product["productNr"] = $lineItem->getPayload()["productNumber"];
  90.                 $product["quantity"] = $lineItem->getQuantity();
  91.                 fputcsv($file$product";");
  92.             }
  93.             die();
  94.         }
  95.     }
  96.     /**
  97.      * @param $file
  98.      * @param $context
  99.      * @return bool|string
  100.      */
  101.     private function importFile($file$context) {
  102.         if (!is_file($file->getPathname())) {
  103.             return $this->productErr "File not found!";
  104.         }
  105.         if($file->getMimeType() === 'text/csv' || $file->getMimeType() === "text/plain") {
  106.             $csv $file->getPathname();
  107.             if (($handle fopen($csv"r")) !== false) {
  108.                 while (($data fgetcsv($handle0";")) !== false) {
  109.                     $orderNumber trim($data[0]);
  110.                     $quantity trim($data[1]);
  111.                     try {
  112.                         $this->addProductToCart($this->cartService->getCart($context->getToken(), $context), $context$orderNumber, (int) $quantity);
  113.                     } catch (Exception $e) {
  114.                         fclose($handle);
  115.                         throw new Exception($e->getMessage());
  116.                     }
  117.                 }
  118.                 fclose($handle);
  119.             }
  120.         }
  121.         return true;
  122.     }
  123.     private function addProductToCart(Cart $cartSalesChannelContext $context$productNrint $quantity 1)
  124.     {
  125.         // Create product line item
  126.         try {
  127.             $criteria = new Criteria();
  128.             $criteria->addFilter(
  129.                 new EqualsFilter("productNumber"$productNr)
  130.             );
  131.             $product $this->productRepository->search($criteria$context->getContext())->first();
  132.             $checkBasket false;
  133.             if($product){
  134.                 $isInBasket $cart->getLineItems()->filterType(LineItem::PRODUCT_LINE_ITEM_TYPE);
  135.                 $checkBasket $this->checkCart($cart$isInBasket$product$quantity$context);
  136.             }
  137.             if(
  138.                 !$checkBasket &&
  139.                 $product &&
  140.                 $quantity 0
  141.             ) {
  142.                 $lineItem $this->factory->create([
  143.                     'id'           => $product->getId(),
  144.                     'type'         => LineItem::PRODUCT_LINE_ITEM_TYPE,
  145.                     'referencedId' => $product->getId(),
  146.                     'quantity'     => $quantity
  147.                 ], $context);
  148.                 $this->cartService->add($cart$lineItem$context);
  149.             } elseif(!$checkBasket) {
  150.                 $this->productErr .= "Product with " $productNr " not found <br>";
  151.             }
  152.         } catch(\Exception $e) {
  153.         }
  154.     }
  155.     private function checkCart($cart$isInBasket$product$quantity$context){
  156.         foreach ($isInBasket as $basket){
  157.             if($basket->getReferencedId() == $product->getId()){
  158.                 $newQuantity $basket->getQuantity() + $quantity;
  159.                 $this->cartService->changeQuantity($cart$basket->getId(), $newQuantity$context);
  160.                 return true;
  161.             }
  162.         }
  163.         return false;
  164.     }
  165. }