magento2 创建订单发货信息,包含Tracking Number和History Comment和Email

功能介绍,通过csv文件上传订单的OrderId和TrackingNumber,添加订单发货信息并修改订单状态

功能界面如:

b7385356fa578c970aece003992aaaabae8.jpg

 

代码文件

一、控制器文件Importallorders.php

<?php

namespace Dotsquares\Imexport\Controller\Adminhtml\Shipstation;

use Magento\Framework\App\Filesystem\DirectoryList;

class Importallorders extends \Magento\Backend\App\Action
{
    public function execute()
    {
        if ($this->getRequest()->getPostValue()){
            $files = $this->getRequest()->getFiles();
            if($files['order_csv']['name'] != ''){
                $data = $this->getRequest()->getPostValue();
                $path_info = pathinfo($files['order_csv']['name']);
                $ex = $path_info['extension'];
                if($ex=="CSV" || $ex=="csv"){
                    try{
                        $uploader = $this->_objectManager->create('Magento\MediaStorage\Model\File\Uploader',['fileId' => 'order_csv']);
                        $uploader->setAllowedExtensions(array('csv'));
                        $uploader->setAllowRenameFiles(false);
                        $uploader->setFilesDispersion(false);
                        $dir = $this->_objectManager->get('\Magento\Framework\App\Filesystem\DirectoryList');
                        $path = $dir->getPath(DirectoryList::MEDIA) . '/dotsquares/ordercsvimport/';
                        $uploader->save($path, $files['order_csv']['name']);
                        
                        //read csv and handle order shipment
                        $result = $this->_objectManager->create('Dotsquares\Imexport\Model\Shipstation')->readCSV($this->_objectManager,$path.$files['order_csv']['name'],$data);
                        if (0 == $result['status']) {
                            $this->messageManager->addError($result['info']);
                        } else {
                            $this->messageManager->addSuccess($result['info']);
                        }
                        
                        $this->_redirect('*/*/orders');
                    }catch (\Exception $e){
                        $this->messageManager->addError('Invalid file type!!');
                        $this->_redirect('*/*/orders');
                    }
                }else{
                    $this->messageManager->addError('Invalid file type!!');
                    $this->_redirect('*/*/orders');
                }
            }else{
                $this->messageManager->addError('Unable to find the import file');
                $this->_redirect('*/*/orders');
            }
        }
    }
}

 

二、上述readCsv()方法所在的文件Shipstation.php

<?php
namespace Dotsquares\Imexport\Model;

class Shipstation extends \Magento\Framework\model\AbstractModel
{
    public function readCSV(&$objectManager,$csvFile,$data)
    {
        /**
         * 文件格式,第一列:Order - Number,第二列:Shipment - Tracking Number;第一行是标题
         */
        $store_id = $data['store_id'];
        $file = fopen($csvFile, 'r');
        $i = 0;//第一行是标题,跳过
        $endLine = 0;
        $errorLine = [];
        feof($file);
        while (!feof($file)){
            $row = fgetcsv($file);
            $i++;
            //第一行是标题,跳过
            if (1 == $i) {
                continue;
            }
            //一整行为空,应该是最后一行了
            if(1 == count($row) && empty($row[0])){
                $errorLine[$i] = 'Line Error.';
                $endLine = $i;
                continue;
            }
            //Order Number 和 Tranking Number 都不能为空
            if(empty($row[0]) || empty($row[1])){
                $errorLine[$i] = 'Line Error.';
                continue;
            }
            
            //开始处理订单发货信息
            if (empty($objectManager)) {
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            }
            $result = $this->insertShipInfo($objectManager,$row[0],$row[1]);
            if (0 == $result['status']) {
                $errorLine[$row[0]] = $result['info'];
            }
            
            //var_dump($result);exit;
        }
        fclose($file);
        
        //错误行里,去掉最后一行
        if ($endLine == $i) {
            unset($errorLine[$i]);
        }
        
        //return
        if (count($errorLine)) {
            return ['status' => 0, 'info' => json_encode($errorLine)];
        } else {
            $num = $i - 2;//共多少记录
            return ['status' => 1, 'info' => 'Success:' . $num];
        }
    }
   
    /**
     *开始处理订单发货信息
     * param $orderId:订单ID
     * param $tranking:发货号码
     * boole
     */
    public function insertShipInfo(&$objectManager,$orderId,$tranking)
    {
        if (empty($objectManager) || empty($orderId) || empty($tranking)) {
            return ['status' => 0, 'info' => 'Params Error.'];
        }
        try {
            // Load the order
            $order = $objectManager->create('Magento\Sales\Model\Order')->loadByAttribute('increment_id', $orderId);
            if ( !$order->getId() ) {
                return ['status' => 0, 'info' => 'Order Not Exist.'];
            }
            
            // Order is complete, continue
            if ('shipped' == $order->getStatus() || 'complete' == $order->getStatus()) {
                return ['status' => 1, 'info' => 'Order Complete.'];
            }
            
            // If is not processing status, continue
            if ('processing' != $order->getStatus()) {
                return ['status' => 0, 'info' => 'Order Is '.$order->getStatus().'.'];
            }
            
            // Check if order has already shipped or can be shipped
            if ( !$order->canShip() ) {
                return ['status' => 0, 'info' => 'Order Can Not Ship.'];
            }
            
            // Initialize the order shipment object
            $convertOrder = $objectManager->create('Magento\Sales\Model\Convert\Order');
            $shipment = $convertOrder->toShipment($order);
            
            // Loop through order items
            foreach ($order->getAllItems() AS $orderItem) {
                // Check if order item is virtual or has quantity to ship
                if (!$orderItem->getQtyInvoiced() || $orderItem->getIsVirtual()) {
                    return ['status' => 0, 'info' => 'Order Item Has Virtual Or Not Has Qty To Ship.'];
                }
                $qtyShipped = $orderItem->getQtyInvoiced();
                // Create shipment item with qty
                $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);
                // Add shipment item to shipment
                $shipment->addItem($shipmentItem);
            }
            
            // Register shipment
            $shipment->register();
            $data = array(
                'carrier_code' => 'usps',
                'title' => 'United States Postal Service',
                'number' => $tranking
            );
            $shipment->getOrder()->setIsInProcess(true);
            //add order history comment
            $history = $shipment->getOrder()->addStatusHistoryComment("Package shipped on 4/8/2019 via USPS First Class Mail. Tracking No ".$tranking,$order->getStatus());
            $history->save();
            
            // Save created shipment and order
            $track = $objectManager->create('Magento\Sales\Model\Order\Shipment\TrackFactory')->create()->addData($data);
            $shipment->addTrack($track)->save();
            $shipment->save();
            $shipment->getOrder()->save();
            // Send email
            $objectManager->create('Magento\Shipping\Model\ShipmentNotifier')->notify($shipment);
            $shipment->save();
            
            return ['status' => 1, 'info' => 'Success.'];
        }  catch (\Exception $e) {
            return ['status' => 0, 'info' => 'Exception.'];
        }
    }
}

转载于:https://my.oschina.net/ganfanghua/blog/3046518

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值