Проблема в создании заказа прагматично с несколькими продуктами - PullRequest
0 голосов
/ 11 мая 2018

Я пытаюсь создать заказ на несколько продуктов, используя приведенный ниже код.Код работает нормально, но возникает одна проблема.Я не знаю, почему при добавлении более одного продукта создается заказ только с одним продуктом, и все количество суммируется с этим.

<?php
namespace Magecomp\Cenpos\Controller\Index;

use Magento\Framework\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Store\Model\StoreManagerInterface;

use Magento\Framework\Controller\ResultFactory; 

class Display extends \Magento\Framework\App\Action\Action
{
    protected $context;
    protected $directory_list;
    protected $cartRepositoryInterface;
    protected $cartManagementInterface;
    protected $_orderRepositoryInterface ;

    /**
     * @var \Magento\Sales\Model\Order\Email\Sender\OrderSender
     */
    protected $orderSender;

    /**
     * @var \Magento\Checkout\Model\Session $checkoutSession
     */
    protected $checkoutSession;

    protected $_messageManager;

    protected $_encryptor;

    protected $_scopeConfig;

    protected $logger;


    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\App\Filesystem\DirectoryList $directory_list,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\Product $product,
        \Magento\Framework\Data\Form\FormKey $formkey,
        \Magento\Quote\Model\QuoteFactory $quote,
        \Magento\Quote\Model\QuoteManagement $quoteManagement,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Sales\Model\Service\OrderService $orderService,
        \Magento\Customer\Model\Session $currentCustomer,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
        \Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender,
        \Magento\Framework\Encryption\EncryptorInterface $encryptor,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
        //\Magento\Sales\Api\OrderRepositoryInterface $orderRepositoryInterface
        ) {
        $this->directory_list = $directory_list; 
        $this->_storeManager = $storeManager;
        $this->_product = $product;
        $this->_formkey = $formkey;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->orderService = $orderService;
        $this->_currentCustomer = $currentCustomer;
        $this->_cart = $cart; 
        $this->cartRepositoryInterface = $cartRepositoryInterface;
        $this->cartManagementInterface = $cartManagementInterface;
        $this->checkoutSession = $checkoutSession;
        $this->orderSender = $orderSender;
        $this->_encryptor = $encryptor;
        $this->_scopeConfig = $scopeConfig;
        //$this->_orderRepositoryInterface = $orderRepositoryInterface;
        $this->_messageManager = $context->getMessageManager();
        parent::__construct($context);
    }

    public function saveShipping() {
        if(isset($_POST['carrier_code']))
        {
            $_SESSION['carrier_code'] = $_POST['carrier_code'];
        }
        return true;
    }

    public function execute()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $cart = $objectManager->get('\Magento\Checkout\Model\Cart');

        $shippingAddress = $cart->getQuote()->getShippingAddress();
        $shippingAddressData = $shippingAddress->getData();

        $Response = $_GET;
        if($Response['message'] == "Approved" && $Response['result'] == "0") {
            $store=$this->_storeManager->getStore();
            $websiteId = $this->_storeManager->getStore()->getWebsiteId();

            $customer=$this->customerFactory->create();
            $customer->setWebsiteId($websiteId);

            $customer->loadByEmail($shippingAddressData['email']);// load customet by email address
            if(!$customer->getEntityId()){
                //If not avilable then create this customer
                $customer->setWebsiteId($websiteId)
                ->setStore($store)
                ->setFirstname($shippingAddressData['firstname'])
                ->setLastname($shippingAddressData['lastname'])
                ->setEmail($shippingAddressData['email'])
                ->setPassword($shippingAddressData['email']);
                $customer->save();
                $customer= $this->customerRepository->getById($customer->getEntityId());
            }

            //init the quote
            $cart_id = $this->cartManagementInterface->createEmptyCart();
            $cart = $this->cartRepositoryInterface->get($cart_id);

            $cart->setStore($store);

            // if you have already had the buyer id, you can load customer directly
            $customer= $this->customerRepository->getById($customer->getEntityId());
            $cart->setCurrency();
            $cart->assignCustomer($customer); //Assign quote to customer

            $productInfo = $this->_cart->getQuote()->getAllItems();
            //add items in quote
            foreach($productInfo as $item){
               $product=$this->_product->load($item->getProductId());
                $product->setPrice($item->getPrice());
                $cart->addProduct(
                    $product,
                    intval($item->getQty())
                    ); 
            }

            $addressData = array(
                'firstname' => $shippingAddressData['firstname'],
                'lastname' => $shippingAddressData['lastname'],
                'street' => $shippingAddressData['street'],
                'city' => $shippingAddressData['city'],
                'postcode' => $shippingAddressData['postcode'],
                'telephone' => $shippingAddressData['telephone'],
                'country_id' => $shippingAddressData['country_id'],
                'region_id' => $shippingAddressData['region_id'],
                'region' => $shippingAddressData['region'],
                );


            //set shipping and billing address
            $quote = $this->quote->create();

            $cart->getBillingAddress()->addData($addressData);
            $cart->getShippingAddress()->addData($addressData); 

            if(isset($_SESSION['carrier_code'])) {
                $shipping_method = $_SESSION['carrier_code'];
            } else {
                $session = $this->_objectManager->get('Magento\Checkout\Model\Session');
                $shipping_method = $session->getQuote()->getShippingAddress()->getShippingMethod();
            }
            $shippingAddress = $cart->getShippingAddress();
            $shippingAddress->setCollectShippingRates(true)
            ->collectShippingRates()
            ->setShippingMethod($shipping_method);
            unset($_SESSION['carrier_code']);

            $cart->setPaymentMethod('cenpos'); //payment method

            //@todo insert a variable to affect the invetory
            $cart->setInventoryProcessed(false);


            $card_type_code = "VI";
            $cart->getPayment()->importData(
                [
                'method'      => 'cenpos',
                'cc_type'   => $card_type_code,
                'cc_number' => '4893772408728522',
                'cc_cid'         => '341',
                'cc_exp_month' => '02',
                'cc_exp_year' => '2022'
                ]
                );

            // Collect total and save
            $cart->collectTotals();

            // Submit the quote and create the order
            $cart->save();
            $cart = $this->cartRepositoryInterface->get($cart->getId());
            $order_id = $this->cartManagementInterface->placeOrder($cart->getId());

            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $orderRepository = $objectManager->create('Magento\Sales\Model\Order')->load($order_id);

            $orderRepository->save();   

            $orderRepository->setEmailSent(true);

            $this->checkoutSession->setForceOrderMailSentOnSuccess(true);

            $this->orderSender->send($orderRepository, true);

            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
            $resultRedirect->setUrl('http://m2gymtest.tpesonline.com/checkout/onepage/success'); 
            return $resultRedirect;

        }
    }

}

Есть ли проблемы в скрипте?Или это может быть проблема с сервером, так как проблема начинает возникать после изменений на сервере. До нескольких дней она работала нормально.

1 Ответ

0 голосов
/ 11 мая 2018

Use \Magento\Catalog\Model\ProductFactory $product вместо \Magento\Catalog\Model\Product $product в аргументе __construct().

И используйте

$product = $this->_product->create()->setStoreId($storeId)->load($item->getId());

для загрузки продукта вместо

$product=$this->_product->load($item->getProductId());

Надеждаэто поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...