b0bfa810 by Vo Van Khoa

Remove event

1 parent 9648fc3f
......@@ -23,18 +23,21 @@ class DefaultRenderer extends \Magento\Sales\Block\Adminhtml\Items\Renderer\Defa
\Magento\Backend\Block\Template\Context $context,
\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
\Magento\CatalogInventory\Api\StockConfigurationInterface $stockConfiguration,
\Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository,
\Magento\Framework\Registry $registry,
array $data = []
) {
$this->_coreRegistry = $registry;
$this->_stockItemRepository = $stockItemRepository;
parent::__construct($context, $stockRegistry, $stockConfiguration, $registry, $data);
}
public function getErrorOutStock($productId) {
$productsId = explode(',',$this->getRequest()->getParam('productsId'));
if(in_array($productId, $productsId)) {
$html = '<div id="messages"><div class="messages"><div class="message message-error error"><div data-ui-id="messages-message-error">This product is out of stock</div></div></div></div>';
return $html;
$_productStock = $this->_stockItemRepository->get($productId);
$html = '';
if(!$_productStock->getIsInStock()) {
$html = '<div class="message message-error error"><div data-ui-id="messages-message-error">This product is out of stock</div></div>';
}
return $html;
}
}
......
<?php
namespace FGCT\OverrideCreateInvoice\Controller\Adminhtml\Order\Invoice;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;
use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;
use Magento\Sales\Model\Order\Email\Sender\ShipmentSender;
use Magento\Sales\Model\Order\ShipmentFactory;
use Magento\Sales\Model\Order\Invoice;
use Magento\Sales\Model\Service\InvoiceService;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Save extends \Magento\Sales\Controller\Adminhtml\Order\Invoice\Save {
/**
* @var InvoiceSender
*/
protected $invoiceSender;
/**
* @var ShipmentSender
*/
protected $shipmentSender;
/**
* @var ShipmentFactory
*/
protected $shipmentFactory;
/**
* @var Registry
*/
protected $registry;
/**
* @var InvoiceService
*/
private $invoiceService;
/**
* @param Action\Context $context
* @param Registry $registry
* @param InvoiceSender $invoiceSender
* @param ShipmentSender $shipmentSender
* @param ShipmentFactory $shipmentFactory
* @param InvoiceService $invoiceService
*/
public function __construct(
Action\Context $context,
Registry $registry,
InvoiceSender $invoiceSender,
ShipmentSender $shipmentSender,
ShipmentFactory $shipmentFactory,
InvoiceService $invoiceService,
\Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository
) {
$this->registry = $registry;
$this->invoiceSender = $invoiceSender;
$this->shipmentSender = $shipmentSender;
$this->shipmentFactory = $shipmentFactory;
$this->invoiceService = $invoiceService;
$this->_stockItemRepository = $stockItemRepository;
parent::__construct($context, $registry, $invoiceSender, $shipmentSender, $shipmentFactory, $invoiceService);
}
public function execute() {
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$formKeyIsValid = $this->_formKeyValidator->validate($this->getRequest());
$isPost = $this->getRequest()->isPost();
if (!$formKeyIsValid || !$isPost) {
$this->messageManager->addError(__('We can\'t save the invoice right now.'));
return $resultRedirect->setPath('sales/order/index');
}
$data = $this->getRequest()->getPost('invoice');
$orderId = $this->getRequest()->getParam('order_id');
if (!empty($data['comment_text'])) {
$this->_objectManager->get(\Magento\Backend\Model\Session::class)->setCommentText($data['comment_text']);
}
try {
$invoiceData = $this->getRequest()->getParam('invoice', []);
$invoiceItems = isset($invoiceData['items']) ? $invoiceData['items'] : [];
/** @var \Magento\Sales\Model\Order $order */
$order = $this->_objectManager->create(\Magento\Sales\Model\Order::class)->load($orderId);
if (!$order->getId()) {
throw new \Magento\Framework\Exception\LocalizedException(__('The order no longer exists.'));
}
if (!$order->canInvoice()) {
throw new \Magento\Framework\Exception\LocalizedException(
__('The order does not allow an invoice to be created.')
);
}
$invoice = $this->invoiceService->prepareInvoice($order, $invoiceItems);
foreach ($invoice->getAllItems() as $item) {
$_productStock = $this->_stockItemRepository->get($item->getProductId());
if(!$_productStock->getIsInStock()) {
$this->messageManager->addError(__('Some of the products are out of stock!'));
return $resultRedirect->setPath('sales/order_invoice/new/*', ['order_id' => $order->getId()]);
}
}
$invoice = false;
if (!$invoice) {
throw new LocalizedException(__('We can\'t save the invoice right now.'));
}
if (!$invoice->getTotalQty()) {
throw new \Magento\Framework\Exception\LocalizedException(
__('You can\'t create an invoice without products.')
);
}
$this->registry->register('current_invoice', $invoice);
if (!empty($data['capture_case'])) {
$invoice->setRequestedCaptureCase($data['capture_case']);
}
if (!empty($data['comment_text'])) {
$invoice->addComment(
$data['comment_text'],
isset($data['comment_customer_notify']),
isset($data['is_visible_on_front'])
);
$invoice->setCustomerNote($data['comment_text']);
$invoice->setCustomerNoteNotify(isset($data['comment_customer_notify']));
}
$invoice->register();
$invoice->getOrder()->setCustomerNoteNotify(!empty($data['send_email']));
$invoice->getOrder()->setIsInProcess(true);
$transactionSave = $this->_objectManager->create(
\Magento\Framework\DB\Transaction::class
)->addObject(
$invoice
)->addObject(
$invoice->getOrder()
);
$shipment = false;
if (!empty($data['do_shipment']) || (int)$invoice->getOrder()->getForcedShipmentWithInvoice()) {
$shipment = $this->_prepareShipment($invoice);
if ($shipment) {
$transactionSave->addObject($shipment);
}
}
$transactionSave->save();
if (!empty($data['do_shipment'])) {
$this->messageManager->addSuccess(__('You created the invoice and shipment.'));
} else {
$this->messageManager->addSuccess(__('The invoice has been created.'));
}
// send invoice/shipment emails
try {
if (!empty($data['send_email'])) {
$this->invoiceSender->send($invoice);
}
} catch (\Exception $e) {
$this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
$this->messageManager->addError(__('We can\'t send the invoice email right now.'));
}
if ($shipment) {
try {
if (!empty($data['send_email'])) {
$this->shipmentSender->send($shipment);
}
} catch (\Exception $e) {
$this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
$this->messageManager->addError(__('We can\'t send the shipment right now.'));
}
}
$this->_objectManager->get(\Magento\Backend\Model\Session::class)->getCommentText(true);
return $resultRedirect->setPath('sales/order/view', ['order_id' => $orderId]);
} catch (LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addError(__('We can\'t save the invoice right now.'));
$this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
}
return $resultRedirect->setPath('sales/*/new', ['order_id' => $orderId]);
}
}
<?php
namespace FGCT\OverrideCreateInvoice\Observer;
use Magento\Framework\Event\ObserverInterface;
class OrderInvoiceSaveAfter implements ObserverInterface {
public $_coreRegistry;
protected $_helper;
public function __construct(
\Magento\Framework\Registry $coreRegistry
) {
$this->_coreRegistry = $coreRegistry;
}
public function execute(\Magento\Framework\Event\Observer $observer) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productsId = $this->_coreRegistry->registry('fgct_overridecreateinvoice_products_out_stock') ?: [];
if(count($productsId)) {
$msg = "Some of the products are out of stock";
//throw new \Exception($msg);
exit('OrderInvoiceSaveAfter');
}
}
}
<?php
namespace FGCT\OverrideCreateInvoice\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Controller\ResultFactory;
class OrderInvoiceSaveBefore implements ObserverInterface {
public $_coreRegistry;
protected $_helper;
public function __construct(
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\App\RequestInterface $request,
\Magento\Framework\App\ResponseFactory $responseFactory,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository,
\Magento\Framework\UrlInterface $url
) {
$this->_coreRegistry = $coreRegistry;
$this->_request = $request;
$this->responseFactory = $responseFactory;
$this->url = $url;
$this->_messageManager = $messageManager;
$this->_stockItemRepository = $stockItemRepository;
}
public function execute(\Magento\Framework\Event\Observer $observer) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderId = $this->_request->getParam('order_id');
$invoice = $observer->getEvent()->getInvoice();
// $order = $invoice->getOrder();
$productManager = $objectManager->create('Magento\Catalog\Model\Product');
$productsOutStock = $productsNotEnoughQty = [];
foreach ($invoice->getAllItems() as $item) {
$name = $item->getName();
// $type = $item->getSku();
$productId = $item->getProductId();
$qty = $item->getQty();
// $product = $productManager->load($productId);
$_productStock = $this->_stockItemRepository->get($productId);
// $_productStock->getQty();
if(!$_productStock->getIsInStock()) {
$productsOutStock[$productId] = $name;
}
if($qty > $_productStock->getQty()) {
$productsNotEnoughQty[$productId] = $_productStock->getQty();
}
}
if(count($productsOutStock)) {
$productsId = array_keys($productsOutStock);
$this->_coreRegistry->register('fgct_overridecreateinvoice_products_out_stock', $productsId, true);
$this->_messageManager->addError(__('Some of the products are out of stock'));
$redirectionUrl = $this->url->getUrl('sales/order_invoice/new/*/product/*/', ['order_id' => $orderId, 'productsId' => implode(',', $productsId)]);
$this->responseFactory->create()->setRedirect($redirectionUrl)->sendResponse();
return $this;
}
}
}
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_order_invoice_save_before">
<observer name="fgc_sales_order_invoice_save_before" instance="FGCT\OverrideCreateInvoice\Observer\OrderInvoiceSaveBefore" />
</event>
<event name="sales_order_invoice_save_after">
<observer name="fgc_sales_order_invoice_save_after" instance="FGCT\OverrideCreateInvoice\Observer\OrderInvoiceSaveAfter" />
</event>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Sales\Block\Adminhtml\Items\Renderer\DefaultRenderer" type="FGCT\OverrideCreateInvoice\Block\Adminhtml\Items\Renderer\DefaultRenderer" />
<preference for="Magento\Sales\Controller\Adminhtml\Order\Invoice\Save" type="FGCT\OverrideCreateInvoice\Controller\Adminhtml\Order\Invoice\Save" />
</config>
......