Skip to content

Commit

Permalink
Added Credit Memo functionality. Created Helper. Implemented method s…
Browse files Browse the repository at this point in the history
…earchOrder. Set v1.2.2
  • Loading branch information
Returnless committed May 10, 2022
1 parent 019e927 commit 8672c38
Show file tree
Hide file tree
Showing 8 changed files with 405 additions and 44 deletions.
18 changes: 18 additions & 0 deletions Api/OrderCreditMemoInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Returnless\Connector\Api;

/**
* Interface OrderCreditMemoInterface
*/
interface OrderCreditMemoInterface
{
/**
* Creates Credit Memo By the Request Params
*
* @api
* @param $requestParams
* @return mixed
*/
public function createCreditMemo($requestParams);
}
66 changes: 66 additions & 0 deletions Controller/Order/Refund.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Returnless\Connector\Controller\Order;

use Magento\Framework\App\Action\Context;
use Returnless\Connector\Model\Api\OrderCreditMemo;
use Returnless\Connector\Model\Config;
use Psr\Log\LoggerInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;

/**
* Class Refund
*/
class Refund extends AbstractController implements HttpPostActionInterface
{
/**
* @var OrderCreditMemo
*/
protected $orderCreditMemo;

/**
* CreditMemo constructor.
*
* @param OrderCreditMemo $orderCreditMemo
* @param Config $config
* @param LoggerInterface $logger
* @param JsonFactory $resultJsonFactory
* @param Context $context
*/
public function __construct(
OrderCreditMemo $orderCreditMemo,
Config $config,
LoggerInterface $logger,
JsonFactory $resultJsonFactory,
Context $context
) {
$this->orderCreditMemo = $orderCreditMemo;
return parent::__construct(
$config,
$logger,
$resultJsonFactory,
$context
);
}

/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$requestData = json_decode($this->getRequest()->getContent(), true);

// validate if Service is enabled
if ($this->checkEnabled()
&& $this->checkSignature($requestData['return_id'])
) {
$response = $this->orderCreditMemo->createCreditMemo($requestData);
// set Response
$this->setResponse($response['return_message'], $response['code'], false, $response);
}

$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData($this->response);
}
}
78 changes: 78 additions & 0 deletions Helper/Data.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

namespace Returnless\Connector\Helper;

use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Sales\Model\OrderRepository;

/**
* Class Data
*/
class Data extends AbstractHelper
{
/**
* @var OrderRepository
*/
protected $orderRepository;

/**
* @var SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;

/**
* Data constructor.
*
* @param OrderRepository $orderRepository
* @param SearchCriteriaBuilder $searchCriteriaBuilder
* @param Context $context
*/
public function __construct(
OrderRepository $orderRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
Context $context
) {
$this->orderRepository = $orderRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;

parent::__construct($context);
}

/**
* @param $incrementId
* @param string $searchKey
* @return \Magento\Framework\DataObject
*/
public function searchOrder($incrementId, $searchKey = 'increment_id')
{
$searchCriteria = $this->searchCriteriaBuilder
->addFilter(
$searchKey,
$incrementId,
'eq'
)
->create();

return $this->orderRepository->getList($searchCriteria)->getFirstItem();
}

/**
* @param $order
* @param $sku
* @return false|mixed
*/
public function getItemBySku($order, $sku)
{
$items = $order->getAllVisibleItems();

foreach($items as $item){
if ($sku == $item->getSku()) {
return $item;
}
}

return false;
}
}
218 changes: 218 additions & 0 deletions Model/Api/OrderCreditMemo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
<?php
namespace Returnless\Connector\Model\Api;

use Returnless\Connector\Api\OrderCreditMemoInterface;
use Psr\Log\LoggerInterface;
use Magento\Framework\Module\ResourceInterface;
use Magento\Store\Model\ResourceModel\Website\CollectionFactory as WebsiteCollectionFactory;
use Returnless\Connector\Helper\Data as RetHelper;
use Magento\Sales\Model\Order\CreditmemoFactory;
use Magento\Sales\Model\Service\CreditmemoService;
use Magento\Sales\Model\Order\Invoice;
use Magento\Sales\Model\Order\Email\Sender\CreditmemoSender;
use Magento\Sales\Controller\Adminhtml\Order\CreditmemoLoader;

/**
* Class OrderCreditMemo
*/
class OrderCreditMemo implements OrderCreditMemoInterface
{
/**
* const NAMESPACE_MODULE
*/
const NAMESPACE_MODULE = 'Returnless_Connector';

/**
* @var LoggerInterface
*/
private $logger;

/**
* @var WebsiteCollectionFactory
*/
protected $websiteCollection;

/**
* @var ResourceInterface
*/
protected $moduleResource;

/**
* @var RetHelper
*/
protected $retHelper;

/**
* @var CreditmemoFactory
*/
protected $creditMemoFactory;

/**
* @var CreditmemoService
*/
protected $creditMemoService;

/**
* @var Invoice
*/
protected $invoice;

/**
* @var CreditmemoSender
*/
protected $creditmemoSender;

/**
* @var CreditmemoLoader
*/
protected $creditmemoLoader;

/**
* OrderCoupon constructor.
*
* @param CreditmemoSender $creditmemoSender
* @param CreditmemoLoader $creditmemoLoader
* @param CreditmemoFactory $creditMemoFactory
* @param CreditmemoService $creditMemoService
* @param Invoice $invoice
* @param RetHelper $retHelper
* @param WebsiteCollectionFactory $websiteCollection
* @param LoggerInterface $logger
* @param ResourceInterface $moduleResource
*/
public function __construct(
CreditmemoSender $creditMemoSender,
CreditmemoLoader $creditMemoLoader,
CreditmemoFactory $creditMemoFactory,
CreditmemoService $creditMemoService,
Invoice $invoice,
RetHelper $retHelper,
WebsiteCollectionFactory $websiteCollection,
LoggerInterface $logger,
ResourceInterface $moduleResource
) {
$this->creditMemoSender = $creditMemoSender;
$this->creditMemoLoader = $creditMemoLoader;
$this->creditMemoFactory = $creditMemoFactory;
$this->creditMemoService = $creditMemoService;
$this->invoice = $invoice;
$this->retHelper = $retHelper;
$this->websiteCollection = $websiteCollection;
$this->logger = $logger;
$this->moduleResource = $moduleResource;
}

/**
* @inheritdoc
*/
public function createCreditMemo($requestParams)
{
$response['installed_module_version'] = $this->moduleResource->getDbVersion(self::NAMESPACE_MODULE);
$response['return_message'] = 'Success!';
$response['code'] = 200;

$order = $this->retHelper->searchOrder($requestParams['order_id']);

$orderId = $order->getId();
if (!$orderId) {
$response['code'] = 404;
$response['return_message'] = __("Order is not found.");

return $response;
}

$creditMemoData = [];
$itemToCredit = [];

$creditMemoData['shipping_amount'] = 0;
$creditMemoData['adjustment_positive'] = 0;
$creditMemoData['adjustment_negative'] = 0;

$creditMemoData['do_offline'] = 0;
if (isset($requestParams['payment_refund'])
&& $requestParams['payment_refund'] == 'on'
) {
$creditMemoData['do_offline'] = 1;
}

$creditMemoData['comment_text'] = '';
if (isset($requestParams['comment_text'])
&& !empty($requestParams['comment_text'])
&& is_string($requestParams['comment_text'])
) {
$creditMemoData['comment_text'] = $requestParams['comment_text'];
}

$creditMemoData['send_email'] = 0;
if (isset($requestParams['email_to_customer'])
&& $requestParams['email_to_customer'] == 'on'
) {
$creditMemoData['send_email'] = 1;
}

foreach ($requestParams['items'] as $requestItem) {
$item = $this->retHelper->getItemBySku($order, $requestItem['sku']);
$orderItemId = $item->getId();

$itemToCredit[$orderItemId] = [
'qty' => $requestItem['qty']
];
}
$creditMemoData['items'] = $itemToCredit;

try {
$this->creditMemoLoader->setOrderId($orderId); //pass order id
$this->creditMemoLoader->setCreditmemo($creditMemoData);

$creditMemo = $this->creditMemoLoader->load();
if ($creditMemo) {
if (!$creditMemo->isValidGrandTotal()) {
$response['code'] = 406;
$response['return_message'] = __('The credit memo\'s total must be positive.');

return $response;
}

if (!empty($creditMemoData['comment_text'])) {
$creditMemo->addComment(
$creditMemoData['comment_text'],
isset($creditMemoData['comment_customer_notify']),
isset($creditMemoData['is_visible_on_front'])
);

$creditMemo->setCustomerNote($creditMemoData['comment_text']);
$creditMemo->setCustomerNoteNotify(isset($creditMemoData['comment_customer_notify']));
}

$creditMemo->getOrder()->setCustomerNoteNotify(!empty($creditMemoData['send_email']));
$this->creditMemoService->refund($creditMemo, (bool)$creditMemoData['do_offline']);

if (!empty($creditMemoData['send_email'])) {
$this->creditMemoSender->send($creditMemo);
}

if ($creditMemo->getEntityId()) {
$entityId = $creditMemo->getEntityId();
$response['result']['entity_id'] = $entityId;
}

if ($creditMemo->getSubtotal()) {
$subtotal = $creditMemo->getSubtotal();
$response['result']['subtotal'] = $subtotal;
}

if ($creditMemo->getGrandTotal()) {
$grandTotal = $creditMemo->getGrandTotal();
$response['result']['grand_total'] = $grandTotal;
}
}
} catch (\Exception $exception) {
$response['code'] = 406;

$this->logger->error($exception->getMessage());
$response['return_message'] = $exception->getMessage();
}

return $response;
}
}
Loading

0 comments on commit 8672c38

Please sign in to comment.