Як програмно створити замовлення в Magento 2?

Одним із багатьох кроків у робочому процесі обробка замовлень є створення замовлення. У більшості випадків клієнти розміщують замовлення з фронтенду. Однак іноді трапляється, що це завдання лягає на плечі менеджерів магазину. Їм може знадобитися допомогти клієнтам, застосувати власні ціни або просто протестувати процес.

Тим не менш, ви можете створювати замовлення з адміністративної панелі . Це один із варіантів. Однак також можливо створювати замовлення в Magento 2 програмно. У цій статті ви дізнаєтеся про два способи зробити це.

Отже, давайте перейдемо одразу до них.

Створення замовлення за допомогою ін'єкції залежностей

Один із найбезпечніших способів – використовувати ін'єкцію залежностей. Наведений нижче код допоможе вам створити замовлення програмно в Magento 2.

<?php

namespace Magefan\OrderEdit\Model;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Quote\Model\QuoteFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Customer\Api\AddressRepositoryInterface;

class CreateOrder
{
  protected $storeManager;

  protected $quoteManagement;

  protected $customerRepository;

  protected $quoteFactory;

  protected $productRepository;

  protected $addressRepository;

  public function __construct(
    StoreManagerInterface $storeManager,
    CartManagementInterface $cartManagement,
    CustomerRepositoryInterface $customerRepository,
    QuoteFactory $quoteFactory,
    ProductRepositoryInterface $productRepository,
    AddressRepositoryInterface $addressRepository
  )
  {
    $this->storeManager = $storeManager;
    $this->quoteManagement = $cartManagement;
    $this->customerRepository = $customerRepository;
    $this->quoteFactory = $quoteFactory;
    $this->productRepository = $productRepository;
    $this->addressRepository = $addressRepository;
  }

  public function createOrder(array $productSkus, string $customerEmail)
  {
    try {
        $customer = $this->customerRepository->get($customerEmail);
    }
    catch (NoSuchEntityException $e) {
      return ['error' => 1, 'msg' => 'Undefined user by email: ' . $customerEmail];
    }

    $quote = $this->quoteFactory->create();

    $store = $this->storeManager->getStore();
    $quote->setStore($store);
    $quote->assignCustomer($customer);

    //add products in quote
    $productQty = 1;
    foreach ($productSkus as $productSku) {
      try {
        $product = $this->productRepository->get($productSku);
        $quote->addProduct($product, $productQty);
      }
      catch (NoSuchEntityException $e) {}
    }

    $billingAddress = null;
    $shippingAddress = null;
    try {
        $billingAddress = $this->addressRepository->getById($customer->getDefaultBilling());
        $shippingAddress = $this->addressRepository->getById($customer->getDefaultShipping());
    }
    catch (NoSuchEntityException $e) {}

    if ($billingAddress) {
        $quote->getBillingAddress()->importCustomerAddressData($billingAddress);
    }

    if ($shippingAddress) {
        $quote->getShippingAddress()->importCustomerAddressData($shippingAddress);
        $shippingAddress = $quote->getShippingAddress();

$shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('flatrate_flatrate');

    }

    $quote->setPaymentMethod('checkmo');
    $quote->setInventoryProcessed(false);
    $quote->save();

    // Set Sales Order Payment
    $quote->getPayment()->importData(['method' => 'checkmo']);

    // Collect Totals & Save Quote
    $quote->collectTotals()->save();

    // Create Order From Quote
    $order = $this->quoteManagement->submit($quote);

    return ['success' => 1, 'Order was successfully placed, order number: ' .
$order->getIncrementId()];

}
}

Створення замовлення за допомогою менеджера об'єктів

Крім того, замовлення можна створити за допомогою Менеджер об'єктів . Однак він, як правило, приховує реальні залежності класу, тому будьте обережні під час його використання.

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get(Magento\Framework\App\State::class);
$state->setAreaCode('adminhtml');

$storeManager = $objectManager->create(\Magento\Store\Model\StoreManagerInterface::class);
$quoteManagement = $objectManager->create(\Magento\Quote\Api\CartManagementInterface::class);
$customerRepository = $objectManager->create(\Magento\Customer\Api\CustomerRepositoryInterface::class);
$quoteFactory = $objectManager->create(\Magento\Quote\Model\QuoteFactory::class);
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$addressRepository = $objectManager->create(\Magento\Customer\Api\AddressRepositoryInterface::class);
$productSkus = ['24-MB06'];
$customerEmail = 'roni_cost@example.com';


try {
  $customer = $customerRepository->get($customerEmail);
}
catch (NoSuchEntityException $e) {
 return ['error' => 1, 'msg' => 'Undefined user by email: ' . $customerEmail];
}

$quote = $quoteFactory->create();

$store = $storeManager->getStore();

$quote->setStore($store);
$quote->assignCustomer($customer);

//add products in quote
$productQty = 1;
foreach ($productSkus as $productSku) {
 try {
    $product = $productRepository->get($productSku);
    $quote->addProduct($product, $productQty);
 }
 catch (NoSuchEntityException $e) {}
}

$billingAddress = null;
$shippingAddress = null;
try {
  $billingAddress = $addressRepository->getById($customer->getDefaultBilling());
  $shippingAddress = $addressRepository->getById($customer->getDefaultShipping());
}
catch (NoSuchEntityException $e) {}

if ($billingAddress) {
   $quote->getBillingAddress()->importCustomerAddressData($billingAddress);
}

if ($shippingAddress) {
   $quote->getShippingAddress()->importCustomerAddressData($shippingAddress);
    $shippingAddress = $quote->getShippingAddress();

$shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('flatrate_flatrate');

}

$quote->setPaymentMethod('checkmo');
$quote->setInventoryProcessed(false);
$quote->save();

// Set Sales Order Payment
$quote->getPayment()->importData(['method' => 'checkmo']);

// Collect Totals & Save Quote
$quote->collectTotals()->save();

// Create Order From Quote
$order = $quoteManagement->submit($quote);

return ['success' => 1, 'Order was successfully placed, order number: ' . $order->getIncrementId()];

Як тільки ви навчитеся створювати замовлення в Magento 2 програмно, ви отримаєте ще одну корисну навичку. Це та багато інших рішень, пов'язаних із замовленнями, таких як отримання замовлення за ідентифікатором приросту , безумовно допоможуть у процесі управління магазином. Обов'язково вивчіть якомога більше, щоб швидше справлятися з різними завданнями розробки.