cancel
Showing results for 
Search instead for 
Did you mean: 

How to override logic for shipment creation?

How to override logic for shipment creation?

Our current integration has issues with uploading shipment/tracking info with the way MSI works. Is there any way to completely ignore inventory checks when uploading tracking information? i.e salable quantity is 0 and all sources for a stock is 0, but uploading tracking information for an order is still possible. Below is a screenshot of the route.

 

Route 

1 REPLY 1

Re: How to override logic for shipment creation?

In Magento 2, creating shipment programmatically is the convenient way to add the new shipment as you need. The following code is all required things you have to run on Magento 2 console.

// Load the order increment ID
$order = $this->_objectManager->create('Magento\Sales\Model\Order')->loadByIncrementID($incrementid);

// OR
$order = $this->_objectManager->create('Magento\Sales\Model\Order')
    ->loadByAttribute('increment_id', '000000001');


//load by order 
$order = $this->_objectManager->create('Magento\Sales\Model\Order')
    ->load('1');

// Check if order can be shipped or has already shipped
if (! $order->canShip()) {
    throw new \Magento\Framework\Exception\LocalizedException(
                    __('You can\'t create an shipment.')
                );
}

// Initialize the order shipment object
$convertOrder = $this->_objectManager->create('Magento\Sales\Model\Convert\Order');
$shipment = $convertOrder->toShipment($order);

// Loop through order items
foreach ($order->getAllItems() AS $orderItem) {
    // Check if order item has qty to ship or is virtual
    if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
        continue;
    }

    $qtyShipped = $orderItem->getQtyToShip();

    // Create shipment item with qty
    $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);

    // Add shipment item to shipment
    $shipment->addItem($shipmentItem);
}

// Register shipment
$shipment->register();

$shipment->getOrder()->setIsInProcess(true);

try {
    // Save created shipment and order
    $shipment->save();
    $shipment->getOrder()->save();

    // Send email
    $this->_objectManager->create('Magento\Shipping\Model\ShipmentNotifier')
        ->notify($shipment);

    $shipment->save();
} catch (\Exception $e) {
    throw new \Magento\Framework\Exception\LocalizedException(
                    __($e->getMessage())
                );
}

Note: Replace Object Manager by Constructor of your module class.

If you have any additional questions please feel free to contact us.