How to create Shipment programmatically in magento 2?

We just need to pass order id in generateShipment($orderId) function from template.
below code snippet is used for generating Shipment in Magento 2, After generating Shipment automatically send the Shipment mail to a customer who has placed the order.

<?php
namespace Rbj\Shipment\Block;

class Shipment extends \Magento\Framework\View\Element\Template
{
public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Sales\Model\Convert\OrderFactory $convertOrderFactory,
        \Magento\Framework\DB\TransactionFactory $transactionFactory,
        \Magento\Sales\Model\Order\Email\Sender\ShipmentSender $shipmentSender,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        array $data = []
    ) {
        $this->orderRepository = $orderRepository;
        $this->orderConverter = $convertOrderFactory->create();
        $this->transactionFactory = $transactionFactory;
        $this->messageManager = $messageManager;
        $this->shipmentSender = $shipmentSender;
        parent::__construct($context, $data);
    }
/**
 * Create Shipment Based on Order Object
 * @param \Magento\Sales\Model\Order $order
 * @return $this
 */
public function generateShipment($orderId)
{
    try {
        $order = $this->orderRepository->get($orderId);
        if (!$order->getId()) {
            throw new \Magento\Framework\Exception\LocalizedException(__('The order no longer exists.'));
        }

        /* check shipment exist for order or not */
        if ($order->canShip())
        {
            // Initialize the order shipment object
            $shipment = $this->orderConverter->toShipment($order);
            foreach ($order->getAllItems() AS $orderItem) {
                // Check if order item has qty to ship or is order is virtual
                if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
                    continue;
                }
                $qtyShipped = $orderItem->getQtyToShip();
                // Create shipment item with qty
                $shipmentItem = $this->orderConverter->itemToShipmentItem($orderItem)->setQty($qtyShipped);
                // Add shipment item to shipment
                $shipment->addItem($shipmentItem);
            }
            // Register shipment
            $shipment->register();

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

            try {
                $transaction = $this->transactionFactory->create()->addObject($shipment)
                    ->addObject($shipment->getOrder())
                    ->save();
                echo $shipmentId = $shipment->getIncrementId();
            } catch (\Exception $e) {
                $this->messageManager->addError(__('We can\'t generate shipment.'));
            }

            if ($shipment) {
                try {
                    $this->shipmentSender->send($shipment);
                } catch (\Exception $e) {
                    $this->messageManager->addError(__('We can\'t send the shipment right now.'));
                }
            }

            return $shipmentId;
        }
    } catch (\Exception $e) {
        $this->messageManager->addError($e->getMessage());
    }

    return true;
}

Call function from the template,

$orderId = 1;
$shipment = $block->generateInvoice($orderId);

Now Check from Admin panel.

Sales -> Order, Order with Id 1 has generated Shipment.

How to Create Invoice programmatically in Magento 2?

Generate an Auto Invoice Programmatically from Magento 2 required an order id. Based on the Order Id, You can fetch Order Object.

Given code, a snippet is used to generate an Invoice in Magento, After generating an invoice automatically sends the invoice mail to a customer who has placed the order.

I have just given a demo to create an invoice with the specified order id, Continue reading “How to Create Invoice programmatically in Magento 2?”

Get orders collection between a date range in magento 2.

We just need to pass start date and end date to get collection between Specific time in Magento 2. We need to filter created_at field using addAttributeToFilter(). Create Block file.
By default created_at field in  sales_order table represent the time of order creation in Magento 2.

<?php
namespace Rbj\Order\Block;

class OrderRange extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
        array $data = []
    ) {
        $this->orderCollectionFactory = $orderCollectionFactory;
        parent::__construct($context, $data);
    }

    /* Order collection between start and end date */
    public function getOrderCollectionByDateRange(){
        $startDate = date("Y-m-d h:i:s",strtotime('2018-1-1')); // start date
        $endDate = strtotime("Y-m-d h:i:s", strtotime('2018-10-1')); // end date

        $orders = $this->orderCollectionFactory->create()
            ->addAttributeToFilter('created_at', array('from'=>$startDate, 'to'=>$endDate));
        return $orders;
    }
?>

Call Function from template file,

$orders = $block->getOrderCollectionByDateRange();

if($orders->getTotalCount() > 0) { 
    foreach($orders as $_order) {
        $orderId = $_order['increment_id'];
        echo "<pre>";print_r($_order);
    }
}

You can get Order collection by date range by the above tricks.