/**
  * @covers \Magento\Shipping\Model\Shipping\LabelGenerator
  * @param array $info
  * @dataProvider labelInfoDataProvider
  */
 public function testAddTrackingNumbersToShipment(array $info)
 {
     $order = $this->getMockBuilder('Magento\\Sales\\Model\\Order')->disableOriginalConstructor()->getMock();
     $order->expects(static::once())->method('getShippingMethod')->with(true)->willReturn($this->getShippingMethodMock());
     /**
      * @var $shipmentMock \Magento\Sales\Model\Order\Shipment|\PHPUnit_Framework_MockObject_MockObject
      */
     $shipmentMock = $this->getMockBuilder('Magento\\Sales\\Model\\Order\\Shipment')->disableOriginalConstructor()->getMock();
     $shipmentMock->expects(static::once())->method('getOrder')->willReturn($order);
     $this->carrierFactory->expects(static::once())->method('create')->with(self::CARRIER_CODE)->willReturn($this->getCarrierMock());
     $labelsMock = $this->getMockBuilder('\\Magento\\Shipping\\Model\\Shipping\\Labels')->disableOriginalConstructor()->getMock();
     $labelsMock->expects(static::once())->method('requestToShipment')->with($shipmentMock)->willReturn($this->getResponseMock($info));
     $this->labelsFactory->expects(static::once())->method('create')->willReturn($labelsMock);
     $this->filesystem->expects(static::once())->method('getDirectoryWrite')->willReturn($this->getMock('Magento\\Framework\\Filesystem\\Directory\\WriteInterface'));
     $this->scopeConfig->expects(static::once())->method('getValue')->with('carriers/' . self::CARRIER_CODE . '/title', ScopeInterface::SCOPE_STORE, null)->willReturn(self::CARRIER_TITLE);
     $this->labelsFactory->expects(static::once())->method('create')->willReturn($labelsMock);
     $trackMock = $this->getMockBuilder('Magento\\Sales\\Model\\Order\\Shipment\\Track')->setMethods(['setNumber', 'setCarrierCode', 'setTitle'])->disableOriginalConstructor()->getMock();
     $i = 0;
     $trackingNumbers = is_array($info['tracking_number']) ? $info['tracking_number'] : [$info['tracking_number']];
     foreach ($trackingNumbers as $trackingNumber) {
         $trackMock->expects(static::at($i++))->method('setNumber')->with($trackingNumber)->willReturnSelf();
         $trackMock->expects(static::at($i++))->method('setCarrierCode')->with(self::CARRIER_CODE)->willReturnSelf();
         $trackMock->expects(static::at($i++))->method('setTitle')->with(self::CARRIER_TITLE)->willReturnSelf();
     }
     $this->trackFactory->expects(static::any())->method('create')->willReturn($trackMock);
     /**
      * @var $requestMock \Magento\Framework\App\RequestInterface|\PHPUnit_Framework_MockObject_MockObject
      */
     $requestMock = $this->getMock('Magento\\Framework\\App\\RequestInterface');
     $this->labelGenerator->create($shipmentMock, $requestMock);
 }
 /**
  * @param array|null $tracks
  * @dataProvider createDataProvider
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testCreate($tracks)
 {
     $orderItem = $this->getMock('Magento\\Sales\\Model\\Order\\Item', ['getId', 'getQtyOrdered'], [], '', false);
     $orderItem->expects($this->any())->method('getId')->willReturn(1);
     $orderItem->expects($this->any())->method('getQtyOrdered')->willReturn(5);
     $shipmentItem = $this->getMock('Magento\\Sales\\Model\\Order\\Shipment\\Item', ['setQty'], [], '', false);
     $shipmentItem->expects($this->once())->method('setQty')->with(5);
     $order = $this->getMock('Magento\\Sales\\Model\\Order', ['getAllItems'], [], '', false);
     $order->expects($this->any())->method('getAllItems')->willReturn([$orderItem]);
     $shipment = $this->getMock('Magento\\Sales\\Model\\Order\\Shipment', ['addItem', 'setTotalQty', 'addTrack'], [], '', false);
     $shipment->expects($this->once())->method('addItem')->with($shipmentItem);
     $shipment->expects($this->once())->method('setTotalQty')->with(5)->willReturn($shipment);
     $this->converter->expects($this->any())->method('toShipment')->with($order)->willReturn($shipment);
     $this->converter->expects($this->any())->method('itemToShipmentItem')->with($orderItem)->willReturn($shipmentItem);
     if ($tracks) {
         $shipmentTrack = $this->getMock('Magento\\Sales\\Model\\Order\\Shipment\\Track', ['addData'], [], '', false);
         if (empty($tracks[0]['number'])) {
             $shipmentTrack->expects($this->never())->method('addData');
             $this->trackFactory->expects($this->never())->method('create');
             $shipment->expects($this->never())->method('addTrack');
             $this->setExpectedException('Magento\\Framework\\Exception\\LocalizedException');
         } else {
             $shipmentTrack->expects($this->once())->method('addData')->willReturnSelf();
             $this->trackFactory->expects($this->once())->method('create')->willReturn($shipmentTrack);
             $shipment->expects($this->once())->method('addTrack')->with($shipmentTrack);
         }
     }
     $this->assertEquals($shipment, $this->subject->create($order, ['1' => 5], $tracks));
 }
 /**
  * @param \Magento\Sales\Model\Order\Shipment $shipment
  * @param RequestInterface $request
  * @return void
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function create(\Magento\Sales\Model\Order\Shipment $shipment, RequestInterface $request)
 {
     $order = $shipment->getOrder();
     $carrier = $this->_carrierFactory->create($order->getShippingMethod(true)->getCarrierCode());
     if (!$carrier->isShippingLabelsAvailable()) {
         throw new \Magento\Framework\Exception\LocalizedException(__('Shipping labels is not available.'));
     }
     $shipment->setPackages($request->getParam('packages'));
     $response = $this->labelFactory->create()->requestToShipment($shipment);
     if ($response->hasErrors()) {
         throw new \Magento\Framework\Exception\LocalizedException(__($response->getErrors()));
     }
     if (!$response->hasInfo()) {
         throw new \Magento\Framework\Exception\LocalizedException(__('Response info is not exist.'));
     }
     $labelsContent = [];
     $trackingNumbers = [];
     $info = $response->getInfo();
     foreach ($info as $inf) {
         if (!empty($inf['tracking_number']) && !empty($inf['label_content'])) {
             $labelsContent[] = $inf['label_content'];
             $trackingNumbers[] = $inf['tracking_number'];
         }
     }
     $outputPdf = $this->combineLabelsPdf($labelsContent);
     $shipment->setShippingLabel($outputPdf->render());
     $carrierCode = $carrier->getCarrierCode();
     $carrierTitle = $this->scopeConfig->getValue('carriers/' . $carrierCode . '/title', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $shipment->getStoreId());
     if (!empty($trackingNumbers)) {
         foreach ($trackingNumbers as $trackingNumber) {
             $track = $this->trackFactory->create()->setNumber($trackingNumber)->setCarrierCode($carrierCode)->setTitle($carrierTitle);
             $shipment->addTrack($track);
         }
     }
 }
 /**
  * @param \Magento\Sales\Model\Order\Shipment $shipment
  * @param array $trackingNumbers
  * @param string $carrierCode
  * @param string $carrierTitle
  *
  * @return void
  */
 private function addTrackingNumbersToShipment(\Magento\Sales\Model\Order\Shipment $shipment, $trackingNumbers, $carrierCode, $carrierTitle)
 {
     foreach ($trackingNumbers as $number) {
         if (is_array($number)) {
             $this->addTrackingNumbersToShipment($shipment, $number, $carrierCode, $carrierTitle);
         } else {
             $shipment->addTrack($this->trackFactory->create()->setNumber($number)->setCarrierCode($carrierCode)->setTitle($carrierTitle));
         }
     }
 }
 /**
  * Adds tracks to the shipment.
  *
  * @param \Magento\Sales\Api\Data\ShipmentInterface $shipment
  * @param array $tracks
  * @throws \Magento\Framework\Exception\LocalizedException
  * @return \Magento\Sales\Api\Data\ShipmentInterface
  */
 protected function prepareTracks(\Magento\Sales\Api\Data\ShipmentInterface $shipment, array $tracks)
 {
     foreach ($tracks as $data) {
         if (empty($data['number'])) {
             throw new \Magento\Framework\Exception\LocalizedException(__('Please enter a tracking number.'));
         }
         $shipment->addTrack($this->trackFactory->create()->addData($data));
     }
     return $shipment;
 }
 /**
  * @param $_shippingInfo
  *
  * @return string
  */
 public function getTrackingUrlByShippingInfo($_shippingInfo)
 {
     $tracking = $this->_trackFactory->create();
     $tracking = $tracking->getCollection()->addFieldToFilter(['entity_id', 'parent_id', 'order_id'], [['eq' => $_shippingInfo->getTrackId()], ['eq' => $_shippingInfo->getShipId()], ['eq' => $_shippingInfo->getOrderId()]])->setPageSize(1)->setCurPage(1)->load();
     foreach ($tracking->getData() as $track) {
         if (isset($track['carrier_code']) && $track['carrier_code'] == \MercadoPago\MercadoEnvios\Model\Carrier\MercadoEnvios::CODE) {
             return $track['description'];
         }
     }
     return '';
 }
 /**
  * Initialize shipment model instance
  *
  * @param RequestInterface $request
  * @return bool|\Magento\Sales\Model\Order\Shipment
  * @throws \Magento\Framework\Model\Exception
  */
 public function load(RequestInterface $request)
 {
     $shipment = false;
     $shipmentId = $request->getParam('shipment_id');
     $orderId = $request->getParam('order_id');
     if ($shipmentId) {
         $shipment = $this->shipmentFactory->create()->load($shipmentId);
     } elseif ($orderId) {
         $order = $this->orderFactory->create()->load($orderId);
         /**
          * Check order existing
          */
         if (!$order->getId()) {
             $this->messageManager->addError(__('The order no longer exists.'));
             return false;
         }
         /**
          * Check shipment is available to create separate from invoice
          */
         if ($order->getForcedShipmentWithInvoice()) {
             $this->messageManager->addError(__('Cannot do shipment for the order separately from invoice.'));
             return false;
         }
         /**
          * Check shipment create availability
          */
         if (!$order->canShip()) {
             $this->messageManager->addError(__('Cannot do shipment for the order.'));
             return false;
         }
         $savedQtys = $this->_getItemQtys($request);
         $shipment = $this->orderServiceFactory->create(array('order' => $order))->prepareShipment($savedQtys);
         $tracks = $request->getPost('tracking');
         if ($tracks) {
             foreach ($tracks as $data) {
                 if (empty($data['number'])) {
                     throw new \Magento\Framework\Model\Exception(__('Please enter a tracking number.'));
                 }
                 $track = $this->trackFactory->create()->addData($data);
                 $shipment->addTrack($track);
             }
         }
     }
     $this->registry->register('current_shipment', $shipment);
     return $shipment;
 }
 /**
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @throws \Exception
  * @throws bool
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $merchantOrder = $observer->getMerchantOrder();
     if (!count($merchantOrder['shipments']) > 0) {
         return;
     }
     $data = $observer->getPayment();
     $order = $this->_coreModel->_getOrder($data["external_reference"]);
     //if order has shipments, status is updated. If it doesn't the shipment is created.
     if ($merchantOrder['shipments'][0]['status'] == 'ready_to_ship') {
         if ($order->hasShipments()) {
             $shipment = $this->_shipment->load($order->getId(), 'order_id');
         } else {
             $shipment = $this->_shipmentFactory->create($order);
             $order->setIsInProcess(true);
         }
         $shipment->setShippingLabel($merchantOrder['shipments'][0]['id']);
         $shipmentInfo = $this->_shipmentHelper->getShipmentInfo($merchantOrder['shipments'][0]['id']);
         $this->_coreHelper->log("Shipment Info", 'mercadopago-notification.log', $shipmentInfo);
         $serviceInfo = $this->_shipmentHelper->getServiceInfo($merchantOrder['shipments'][0]['service_id'], $merchantOrder['site_id']);
         $this->_coreHelper->log("Service Info by service id", 'mercadopago-notification.log', $serviceInfo);
         if ($shipmentInfo && isset($shipmentInfo->tracking_number)) {
             $tracking['number'] = $shipmentInfo->tracking_number;
             $tracking['description'] = str_replace('#{trackingNumber}', $shipmentInfo->tracking_number, $serviceInfo->tracking_url);
             $tracking['title'] = self::CODE;
             $existingTracking = $this->_trackFactory->create()->load($shipment->getOrderId(), 'order_id');
             if ($existingTracking->getId()) {
                 $track = $shipment->getTrackById($existingTracking->getId());
                 $track->setNumber($tracking['number'])->setDescription($tracking['description'])->setTitle($tracking['title'])->save();
             } else {
                 $track = $this->_trackFactory->create()->addData($tracking);
                 $track->setCarrierCode(\MercadoPago\MercadoEnvios\Model\Carrier\MercadoEnvios::CODE);
                 $shipment->addTrack($track);
                 $shipment->save();
             }
             $this->_coreHelper->log("Track added", 'mercadopago-notification.log', $track);
         }
         $this->_transaction->addObject($order)->save();
     }
 }