Skip to content

Commit

Permalink
Merge pull request #68 from Trunkrs/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
fmsthird authored Sep 12, 2023
2 parents bc142ac + 96efb95 commit 0bde78f
Show file tree
Hide file tree
Showing 16 changed files with 297 additions and 30 deletions.
22 changes: 22 additions & 0 deletions Block/Adminhtml/Grid/Order/TrunkrsPdfAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Trunkrs\Carrier\Block\Adminhtml\Grid\Order;

use Magento\Backend\Block\Template;
use Magento\Framework\View\Element\BlockInterface;

class TrunkrsPdfAction extends Template implements BlockInterface
{
/**
* @var string
*/
protected $_template = 'Trunkrs_Carrier::order/grid/trunkrsPdfAction.phtml';

/**
* @return string
*/
public function getTrunkrsDownloadActionUrl()
{
return $this->getUrl('trunkrs/order/CreateShipmentAndPrintPackingSlips');
}
}
5 changes: 4 additions & 1 deletion Controller/Adminhtml/LabelAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@

abstract class LabelAbstract extends Action
{
const TRUNKRS_SHIPPING_CODE = 'trunkrsShipping_trunkrsShipping';
const TRUNKRS_LABEL_IN_PACKINGSLIPS = 'trunkrs_packingslips';
const CARRIER_CODE = 'trunkrsShipping';
/**
* @var GetLabels
*/
Expand Down Expand Up @@ -42,7 +45,7 @@ public function __construct(
Context $context,
GetLabels $getLabels,
GetPdf $getPdf,
GetPackingslip $getPackingSlip,
GetPackingslip $getPackingSlip
) {
parent::__construct($context);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@

use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NotFoundException;
use Magento\Sales\Api\Data\ShipmentInterface;
use Magento\Sales\Model\Convert\Order;
use Magento\Sales\Model\Order\Shipment;
use Magento\Sales\Model\ResourceModel\Order\Shipment\CollectionFactory;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;
use Magento\Shipping\Model\Shipping\LabelGenerator;
Expand All @@ -17,18 +20,24 @@
use setasign\Fpdi\PdfParser\PdfParserException;
use Trunkrs\Carrier\Controller\Adminhtml\LabelAbstract;
use Trunkrs\Carrier\Controller\Adminhtml\PdfDownload as GetPdf;
use Trunkrs\Carrier\Helper\Data;
use Trunkrs\Carrier\Service\Shipment\Labelling\GetLabels;
use Trunkrs\Carrier\Service\Shipment\Packingslip\GetPackingslip;

class PrintLabelAndPackingSlips extends LabelAbstract
class CreateShipmentAndPrintPackingSlips extends LabelAbstract
{
const TRUNKRS_SHIPPING_CODE = 'trunkrsShipping_trunkrsShipping';
const TRUNKRS_LABEL_IN_PACKINGSLIPS = 'trunkrs_packingslips';

/**
* @var array
*/
protected $orderIds = [];
/**
* @param Data $helper
*/
public $helper;
/**
* @var Order
*/
protected $convertOrder;
/**
* @var OrderCollectionFactory
*/
Expand Down Expand Up @@ -64,6 +73,8 @@ class PrintLabelAndPackingSlips extends LabelAbstract

/**
* @param Context $context
* @param Data $helper
* @param Order $convertOrder
* @param GetLabels $getLabels
* @param GetPdf $getPdf
* @param GetPackingslip $getPackingSlip
Expand All @@ -78,6 +89,8 @@ class PrintLabelAndPackingSlips extends LabelAbstract
*/
public function __construct(
Context $context,
Data $helper,
Order $convertOrder,
GetLabels $getLabels,
GetPdf $getPdf,
GetPackingslip $getPackingSlip,
Expand All @@ -88,8 +101,10 @@ public function __construct(
ShipmentRepositoryInterface $shipmentRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
LoggerInterface $logger,
Filter $filter,
Filter $filter
) {
$this->helper = $helper;
$this->convertOrder = $convertOrder;
$this->collectionFactory = $collectionFactory;
$this->orderCollectionFactory = $orderCollectionFactory;
$this->fileFactory = $fileFactory;
Expand All @@ -102,8 +117,8 @@ public function __construct(
}

/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|null
* @throws NotFoundException|PdfParserException|\Zend_Pdf_Exception
* @return ResponseInterface|null
* @throws NotFoundException|PdfParserException|\Zend_Pdf_Exception|LocalizedException
*/
public function execute()
{
Expand All @@ -117,7 +132,7 @@ public function execute()
}

foreach ($collection as $order) {
$trunkrsShipment = $order->getShippingMethod() === $this::TRUNKRS_SHIPPING_CODE;
$trunkrsShipment = $order->getShippingMethod() === self::TRUNKRS_SHIPPING_CODE;
if($trunkrsShipment) {
$this->orderIds[] = $order->getId();
$this->handleShipmentDataFromOrder($order);
Expand All @@ -126,7 +141,7 @@ public function execute()

if (empty($this->orderIds) || empty($this->labels)) {
$this->messageManager->addErrorMessage(
__('No document generated. Trunkrs shipment not found.')
__('No document generated. Selected order/s not for Trunkrs.')
);
return $this->_redirect($this->_redirect->getRefererUrl());
}
Expand All @@ -138,25 +153,67 @@ public function execute()
* @param $order
* @return void
* @throws NotFoundException|PdfParserException|\Zend_Pdf_Exception
* @throws LocalizedException
*/
private function handleShipmentDataFromOrder($order)
{
$shipments = $this->getShipmentDataByOrderId($order->getId());

if (!$shipments) {
return;
// create Trunkrs shipment
// check whether an order can be shipped or not
if ($order->canShip()) {
$shippingName = $order->getShippingMethod();
if ($shippingName === self::TRUNKRS_SHIPPING_CODE) {
$shipments = $this->createShipment($order);
}
}
}

$this->loadLabels($shipments);
}

/**
* @param $order
* @return Shipment
* @throws LocalizedException
*/
private function createShipment($order)
{
$orderShipment = $this->convertOrder->toShipment($order);
foreach ($order->getAllItems() as $orderItem) {
// Check virtual if item has qty and not virtual type
if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
continue;
}

$qty = $orderItem->getQtyToShip();
$shipmentItem = $this->convertOrder->itemToShipmentItem($orderItem)->setQty($qty);

$orderShipment->addItem($shipmentItem);
}

$orderShipment->register();

$orderShipment->getOrder()->setState(\Magento\Sales\Model\Order::STATE_PROCESSING);
$orderShipment->getOrder()->setStatus('processing');
$orderShipment->getOrder()->save();

// save created Order Shipment
$orderShipment->save();

$this->helper->sendTrunkrsShipment($order, $orderShipment);

return $orderShipment;
}

/**
* Shipment by Order id
*
* @param int $orderId
* @param $orderId
* @return ShipmentInterface[]|null
*/
public function getShipmentDataByOrderId(int $orderId)
public function getShipmentDataByOrderId($orderId)
{
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('order_id', $orderId)->create();
Expand Down
2 changes: 1 addition & 1 deletion Controller/Adminhtml/PdfDownload.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class PdfDownload
*/
public function __construct(
FileFactory $fileFactory,
PackingslipGenerate $packingslipGenerator,
PackingslipGenerate $packingslipGenerator
)
{
$this->fileFactory = $fileFactory;
Expand Down
93 changes: 92 additions & 1 deletion Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\Data\ShipmentTrackInterfaceFactory;
use Magento\Store\Model\ScopeInterface;
use Psr\Log\LoggerInterface;
use Trunkrs\Carrier\Model\Carrier\Shipping;

class Data extends AbstractHelper
{
Expand All @@ -17,13 +21,25 @@ class Data extends AbstractHelper
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var ShipmentTrackInterfaceFactory
*/
private $trackFactory;
/**
* @var LoggerInterface
*/
protected $logger;

public function __construct(
Context $context,
ScopeConfigInterface $scopeConfig
ScopeConfigInterface $scopeConfig,
ShipmentTrackInterfaceFactory $trackFactory,
LoggerInterface $logger
)
{
$this->scopeConfig = $scopeConfig;
$this->trackFactory = $trackFactory;
$this->logger = $logger;
parent::__construct($context);
}

Expand Down Expand Up @@ -145,4 +161,79 @@ public static function parse8601Date(string $dateString): DateTime

return $result;
}

/**
* @param $order
* @param $shipment
* @return void
* @throws LocalizedException
*/
public function sendTrunkrsShipment($order, $shipment)
{
try {
// post shipment to Shipping portal
$urlHost = $this->getCreateShipmentEndpoint();
$client = new \GuzzleHttp\Client();

$addressData = $order->getShippingAddress();

$singleShipmentBody = [
'reference' => $order->getIncrementId(),
'recipient' => [
'name' => $order->getCustomerName(),
'email' => $addressData->getEmail(),
'phoneNumber' => $addressData->getTelephone(),
'location' => [
'address' => implode(' ', $addressData->getStreet()),
'postalCode' => $addressData->getPostcode(),
'city' => $addressData->getCity(),
'country' => $addressData->getCountryId()
]
]
];

$intendedDeliveryDate = $order->getTrunkrsDeliveryDate();
if(!empty($intendedDeliveryDate)) {
$singleShipmentBody['intendedDeliveryDate'] = $intendedDeliveryDate;
}

$response = $client->post($urlHost, [
'headers' => [
'Authorization' => sprintf('Bearer %s', $this->getAccessToken()),
'Content-Type' => 'application/json; charset=utf-8'],
'json' => ['shipments' => [$singleShipmentBody]]
]);

$trunkrsObj = json_decode($response->getBody());
$trunkrsNumber = $trunkrsObj->success[0]->trunkrsNumber;
$labelUrl = $trunkrsObj->success[0]->labelUrl;

$this->setTrack($shipment, $trunkrsNumber, $labelUrl);

$shipment->save();
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
throw new LocalizedException(
__($e->getMessage())
);
}
}

/**
* @param $shipment
* @param $trunkrsNumber
* @param $labelUrl
* @return void
*/
private function setTrack($shipment, $trunkrsNumber, $labelUrl)
{
$track = $this->trackFactory->create();
$track->setCarrierCode(self::CARRIER_CODE);
$track->setTitle(Shipping::TRUNKRS);
$track->setTrackNumber($trunkrsNumber);

$shipment->addTrack($track)
->setShippingAddressId($trunkrsNumber)
->setShippingLabel(file_get_contents($labelUrl));
}
}
6 changes: 4 additions & 2 deletions Observer/TrunkrsSaveShipmentData.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Trunkrs\Carrier\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order;
use Trunkrs\Carrier\Helper\Data;
use Trunkrs\Carrier\Model\Carrier\Shipping;

Expand Down Expand Up @@ -111,6 +112,9 @@ public function execute(\Magento\Framework\Event\Observer $observer)

// Save created Order Shipment
$orderShipment->save();

$orderShipment->getOrder()->setState(Order::STATE_PROCESSING);
$orderShipment->getOrder()->setStatus('processing');
$orderShipment->getOrder()->save();

try {
Expand Down Expand Up @@ -149,8 +153,6 @@ public function execute(\Magento\Framework\Event\Observer $observer)
$trunkrsNumber = $trunkrsObj->success[0]->trunkrsNumber;
$labelUrl = $trunkrsObj->success[0]->labelUrl;

$orderShipment->save();

$track = $this->trackFactory->create();
$track->setCarrierCode(self::CARRIER_CODE);
$track->setTitle(Shipping::TRUNKRS);
Expand Down
3 changes: 2 additions & 1 deletion Observer/TrunkrsShipmentSaveAfter.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ public function execute(Observer $observer)
$trunkrsNumber = $trunkrsObj->success[0]->trunkrsNumber;
$labelUrl = $trunkrsObj->success[0]->labelUrl;

$order->setState(Order::STATE_PROCESSING);
$order->setStatus('processing');
$order->save();

$track = $this->trackFactory->create();
Expand All @@ -131,7 +133,6 @@ public function execute(Observer $observer)
->setShippingLabel(file_get_contents($labelUrl));

$shipment->save();
$order->setStatus('complete');
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
throw new \Magento\Framework\Exception\LocalizedException(
Expand Down
2 changes: 1 addition & 1 deletion Service/Shipment/Labelling/GetLabels.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class GetLabels
* @param ShipmentRepositoryInterface $shipmentRepository
*/
public function __construct(
ShipmentRepositoryInterface $shipmentRepository,
ShipmentRepositoryInterface $shipmentRepository
)
{
$this->shipmentRepository = $shipmentRepository;
Expand Down
Loading

0 comments on commit 0bde78f

Please sign in to comment.