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

Процес управління замовленнями у Magento 2 складається з численних кроків. Одним з останніх є створення відправлення. Це відносно просте завдання, але корисно знати, як впоратися з ним якомога швидше.

З одного боку, ви можете створити відправлення з адміністративної панелі . Цей метод повністю керований і не займає багато часу. З іншого боку, ви можете віддати перевагу альтернативі — створити відправлення в Magento програмно. І в цій статті ви дізнаєтеся про це більше.

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

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

<?php

namespace Vendor\ModuleName;
class ClassName
{
    public $orderRepository;
    public $convertOrder;
    public $shipmentNotifier;
    public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ) {
        $this->productRepository = $productRepository;
    }
    public function createShipmentForOrder($orderId)
    {
        $order = $this->orderRepository->get($orderId);
        if (!$order->canShip()) {
            throw new \Magento\Framework\Exception\LocalizedException(
                __("You can't create the Shipment of this order.")
            );
        }
        $orderShipment = $this->convertOrder->toShipment($order);
        foreach ($order->getAllItems() as $orderItem) {
            // Check virtual item and item Quantity
            if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
                continue;
            }
            $qty = $orderItem->getQtyToShip();
            $shipmentItem = $this->convertOrder->itemToShipmentItem($orderItem)->setQty($qty);
            $orderShipment->addItem($shipmentItem);
        }
        $orderShipment->register();
        $orderShipment->getOrder()->setIsInProcess(true);
        // Save created Order Shipment
        $orderShipment->save();
        $orderShipment->getOrder()->save();
        $this->shipmentNotifier->notify($orderShipment);
    }
}

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

Хоча це також широко відомий спосіб роботи з завданнями Magento, слід бути обережним, працюючи з ним, оскільки він приховує реальні залежності класу.

<?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');
$orderRepository = $objectManager->create(\Magento\Sales\Api\OrderRepositoryInterface::class);
$convertOrder = $objectManager->create(\Magento\Sales\Model\Convert\Order::class);
$shipmentNotifier = $objectManager->create(\Magento\Shipping\Model\ShipmentNotifier::class);
$orderId = 26;
$order = $orderRepository->get($orderId);
if (!$order->canShip()) {
   throw new \Magento\Framework\Exception\LocalizedException(
       __("You can't create the Shipment of this order.")
   );
}
$orderShipment = $convertOrder->toShipment($order);
foreach ($order->getAllItems() as $orderItem) {
   // Check virtual item and item Quantity
   if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
       continue;
   }
   $qty = $orderItem->getQtyToShip();
   $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qty);
   $orderShipment->addItem($shipmentItem);
}
$orderShipment->register();
$orderShipment->getOrder()->setIsInProcess(true);
// Save created Order Shipment
$orderShipment->save();
$orderShipment->getOrder()->save();
// Send Shipment Email
$shipmentNotifier->notify($orderShipment);

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

Однак може статися так, що клієнти захочуть скасувати відправлення, навіть якщо ви його вже створили. Тому буде корисно дізнатися, як скасувати відправлення в Magento 2 уникнути будь-яких проблем під час обробки замовлень.