Skip to content

Commit

Permalink
Add order status support and fix issue with Api response (#102)
Browse files Browse the repository at this point in the history
* Add order status support and fix issue with Api response

* Update README

Co-authored-by: Maksymilian Strzyżewski <[email protected]>
  • Loading branch information
mstrzyzewski and Maksymilian Strzyżewski authored Jan 30, 2022
1 parent 41bc536 commit f01ff02
Show file tree
Hide file tree
Showing 14 changed files with 437 additions and 21 deletions.
92 changes: 92 additions & 0 deletions Block/Adminhtml/Config/Form/Field/OrderStatuses.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

namespace Macopedia\Allegro\Block\Adminhtml\Config\Form\Field;

use Macopedia\Allegro\Block\Adminhtml\Config\Form\Field\Renderer\AllegroOrderStatuses;
use Macopedia\Allegro\Block\Adminhtml\Config\Form\Field\Renderer\MagentoOrderStatuses;
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\LocalizedException;

class OrderStatuses extends AbstractFieldArray
{
/** @var MagentoOrderStatuses */
protected $magentoBlockOptions;

/** @var AllegroOrderStatuses */
protected $allegroBlockOptions;

/**
* @inheritdoc
*/
protected function _prepareToRender()
{
$this->addColumn('allegro_code', [
'label' => __('Allegro order status'),
'class' => 'required-entry',
'renderer' => $this->getAllegroStatusesRenderer()
]);
$this->addColumn('magento_code', [
'label' => __('Magento order status'),
'class' => 'required-entry',
'renderer' => $this->getMagnetoStatusesRenderer()
]);

$this->_addAfter = false;
$this->_addButtonLabel = __('Add status');
}

/**
* @return MagentoOrderStatuses
* @throws LocalizedException
*/
protected function getMagnetoStatusesRenderer()
{
if (!$this->magentoBlockOptions) {
$this->magentoBlockOptions = $this->getLayout()->createBlock(
MagentoOrderStatuses::class,
'',
['data' => ['is_render_to_js_template' => true]]
);
}

return $this->magentoBlockOptions;
}

/**
* @return AllegroOrderStatuses
* @throws LocalizedException
*/
protected function getAllegroStatusesRenderer()
{
if (!$this->allegroBlockOptions) {
$this->allegroBlockOptions = $this->getLayout()->createBlock(
AllegroOrderStatuses::class,
'',
['data' => ['is_render_to_js_template' => true]]
);
}

return $this->allegroBlockOptions;
}

/**
* Prepare existing row data object.
*
* @param DataObject $row
* @throws LocalizedException
*/
protected function _prepareArrayRow(DataObject $row)
{
$options = [];
$customAttribute = $row->getData('magento_code');
$key = 'option_' . $this->getMagnetoStatusesRenderer()->calcOptionHash($customAttribute);
$options[$key] = 'selected="selected"';
$row->setData('option_extra_attrs', $options);

$customAttribute = $row->getData('allegro_code');
$key = 'option_' . $this->getAllegroStatusesRenderer()->calcOptionHash($customAttribute);
$options[$key] = 'selected="selected"';
$row->setData('option_extra_attrs', $options);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Macopedia\Allegro\Block\Adminhtml\Config\Form\Field\Renderer;

use Magento\Framework\View\Element\Html\Select;

class AllegroOrderStatuses extends Select
{
/**
* @param string $value
* @return $this
*/
public function setInputName($value)
{
return $this->setName($value);
}

/**
* @return array
*/
public function getAllegroOrderStatuses()
{
return [
'NEW' => __('NEW'),
'PROCESSING' => __('PROCESSING'),
'READY_FOR_SHIPMENT' => __('READY FOR SHIPMENT'),
'READY_FOR_PICKUP' => __('READY FOR PICKUP'),
'SENT' => __('SENT'),
'PICKED_UP' => __('PICKED UP'),
'CANCELLED' => __('CANCELLED')
];
}
/**
* @return Select
*/
protected function _prepareLayout()
{
$this->setOptions(
$this->getAllegroOrderStatuses()
);
return parent::_prepareLayout();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Macopedia\Allegro\Block\Adminhtml\Config\Form\Field\Renderer;

use Magento\Framework\View\Element\Context;
use Magento\Framework\View\Element\Html\Select;
use Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory;

class MagentoOrderStatuses extends Select
{
/**
* @var CollectionFactory
*/
protected $orderStatusCollectionFactory;

/**
* @param CollectionFactory $orderStatusCollectionFactory
* @param Context $context
* @param array $data
*/
public function __construct(
CollectionFactory $orderStatusCollectionFactory,
Context $context,
array $data = []
) {
parent::__construct($context, $data);
$this->orderStatusCollectionFactory = $orderStatusCollectionFactory;
}

/**
* @param $value
* @return $this
*/
public function setInputName($value)
{
return $this->setName($value);
}

/**
* @return $this
*/
protected function _prepareLayout()
{
$collection = $this->orderStatusCollectionFactory->create()->joinStates();
foreach ($collection as $item) {
$this->addOption($item->getStatus(), __($item->getLabel()));
}

return parent::_prepareLayout();
}
}
70 changes: 70 additions & 0 deletions Model/AllegroOrderStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

namespace Macopedia\Allegro\Model;

use Macopedia\Allegro\Logger\Logger;
use Macopedia\Allegro\Model\ResourceModel\Order\CheckoutForm;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Sales\Model\Order;

class AllegroOrderStatus
{
const STATUSES_MAPPING_CONFIG_KEY = 'allegro/order/mapping';

/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;

/**
* @var CheckoutForm
*/
protected $checkoutForm;

/**
* @var Logger
*/
protected $logger;

/**
* @param ScopeConfigInterface $scopeConfig
* @param CheckoutForm $checkoutForm
* @param Logger $logger
*/
public function __construct(
ScopeConfigInterface $scopeConfig,
CheckoutForm $checkoutForm,
Logger $logger
) {
$this->scopeConfig = $scopeConfig;
$this->checkoutForm = $checkoutForm;
$this->logger = $logger;
}

/**
* @param Order $order
* @return void
*/
public function updateOrderStatus(Order $order)
{
$statusesMapping = $this->scopeConfig->getValue(self::STATUSES_MAPPING_CONFIG_KEY);
$statusesMapping = json_decode($statusesMapping, true);
$statusesMapping = array_column($statusesMapping, 'allegro_code', 'magento_code');

$magentoStatus = $order->getStatus();
$checkoutFormId = $order->getExternalId() ?: $order->getExtensionAttributes()->getExternalId();
if (!isset($statusesMapping[$magentoStatus]) || !$checkoutFormId) {
return;
}

try {
$this->checkoutForm->changeOrderStatus($checkoutFormId, $statusesMapping[$magentoStatus]);
$this->logger->info('Status on Allegro for order ' . $order->getRemoteIp() . ' has been updated');
} catch (\Exception $e) {
$this->logger->exception(
$e,
'Error while trying to update order ' . $order->getIncrementId() . ' status on Allegro: ' . $e->getMessage()//phpcs:ignore
);
}
}
}
10 changes: 9 additions & 1 deletion Model/Api/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,14 @@ private function sendHttpRequest(TokenInterface $token, Request $request)
public function getResponse(GuzzleClient $client, string $method, string $uri, array $params)
{
$response = $client->request($method, $uri, $params);
return $response->getBody()->getContents();
$contents = $response->getBody()->getContents();

if (empty($contents)) {
return $this->json->serialize(
['statusCode' => $response->getStatusCode(), 'reasonPhrase' => $response->getReasonPhrase()]
);
}

return $contents;
}
}
74 changes: 74 additions & 0 deletions Model/Config/Backend/OrderStatuses.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace Macopedia\Allegro\Model\Config\Backend;

use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Value as ConfigValue;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\SerializerInterface;

class OrderStatuses extends ConfigValue
{
/** @var SerializerInterface */
private $serializer;

/**
* @param SerializerInterface $serializer
* @param Context $context
* @param Registry $registry
* @param ScopeConfigInterface $config
* @param TypeListInterface $cacheTypeList
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
SerializerInterface $serializer,
Context $context,
Registry $registry,
ScopeConfigInterface $config,
TypeListInterface $cacheTypeList,
AbstractResource $resource = null,
AbstractDb $resourceCollection = null,
array $data = []
) {
$this->serializer = $serializer;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}

/**
* @return void
*/
public function beforeSave()
{
/** @var array $value */
$value = $this->getValue();
unset($value['__empty']);
array_walk_recursive($value, function (&$v) {
$v = trim($v);
});
$encodedValue = $this->serializer->serialize($value);

$this->setValue($encodedValue);
}

/**
* @return void
*/
protected function _afterLoad()
{
/** @var string $value */
$value = $this->getValue();
if ($value) {
$decodedValue = $this->serializer->unserialize($value);
} else {
$decodedValue = '';
}

$this->setValue($decodedValue);
}
}
23 changes: 19 additions & 4 deletions Model/ResourceModel/Order/CheckoutForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Macopedia\Allegro\Model\ResourceModel\Order;

use Macopedia\Allegro\Model\Api\ClientException;
use Macopedia\Allegro\Model\Api\ClientResponseErrorException;
use Macopedia\Allegro\Model\Api\ClientResponseException;
use Macopedia\Allegro\Model\ResourceModel\AbstractResource;

/**
Expand All @@ -14,8 +16,8 @@ class CheckoutForm extends AbstractResource
* @param $checkoutFormId
* @return array
* @throws ClientException
* @throws \Macopedia\Allegro\Model\Api\ClientResponseErrorException
* @throws \Macopedia\Allegro\Model\Api\ClientResponseException
* @throws ClientResponseErrorException
* @throws ClientResponseException
*/
public function getCheckoutForm($checkoutFormId)
{
Expand All @@ -27,11 +29,24 @@ public function getCheckoutForm($checkoutFormId)
* @param array $shippingData
* @return array
* @throws ClientException
* @throws \Macopedia\Allegro\Model\Api\ClientResponseErrorException
* @throws \Macopedia\Allegro\Model\Api\ClientResponseException
* @throws ClientResponseErrorException
* @throws ClientResponseException
*/
public function shipment($checkoutFormId, array $shippingData)
{
return $this->requestPost('order/checkout-forms/' . $checkoutFormId . '/shipments', $shippingData);
}

/**
* @param $checkoutFormId
* @param string $status
* @return array
* @throws ClientException
* @throws ClientResponseErrorException
* @throws ClientResponseException
*/
public function changeOrderStatus($checkoutFormId, string $status)
{
return $this->requestPut('order/checkout-forms/' . $checkoutFormId . '/fulfillment', ['status' => $status]);
}
}
Loading

0 comments on commit f01ff02

Please sign in to comment.