ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
+55
View File
@@ -0,0 +1,55 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Api\Data;
interface LocationInterface
{
const NAME = 'name';
const LOCATION_ID = 'location_id';
const SOURCE_CODE = 'source_code';
/**
* Get location_id
* @return string|null
*/
public function getLocationId();
/**
* Set location_id
* @param string $locationId
* @return \JR\NetSuite\Api\Data\LocationInterface
*/
public function setLocationId($locationId);
/**
* Get name
* @return string|null
*/
public function getName();
/**
* Set name
* @param string $name
* @return \JR\NetSuite\Api\Data\LocationInterface
*/
public function setName($name);
/**
* Get source_code
* @return string|null
*/
public function getSourceCode();
/**
* Set source_code
* @param string $sourceCode
* @return \JR\NetSuite\Api\Data\LocationInterface
*/
public function setSourceCode($sourceCode);
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Api\Data;
interface LocationSearchResultsInterface extends \Magento\Framework\Api\SearchResultsInterface
{
/**
* Get location list.
* @return \JR\NetSuite\Api\Data\LocationInterface[]
*/
public function getItems();
/**
* Set name list.
* @param \JR\NetSuite\Api\Data\LocationInterface[] $items
* @return $this
*/
public function setItems(array $items);
}
+61
View File
@@ -0,0 +1,61 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Api;
use Magento\Framework\Api\SearchCriteriaInterface;
interface LocationRepositoryInterface
{
/**
* Save location
* @param \JR\NetSuite\Api\Data\LocationInterface $location
* @return \JR\NetSuite\Api\Data\LocationInterface
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function save(
\JR\NetSuite\Api\Data\LocationInterface $location
);
/**
* Retrieve location
* @param string $locationId
* @return \JR\NetSuite\Api\Data\LocationInterface
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function get($locationId);
/**
* Retrieve location matching the specified criteria.
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return \JR\NetSuite\Api\Data\LocationSearchResultsInterface
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getList(
SearchCriteriaInterface $searchCriteria
);
/**
* Delete location
* @param \JR\NetSuite\Api\Data\LocationInterface $location
* @return bool true on success
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function delete(
\JR\NetSuite\Api\Data\LocationInterface $location
);
/**
* Delete location by ID
* @param string $locationId
* @return bool true on success
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function deleteById($locationId);
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace JR\NetSuite\Api;
interface SyncInterface
{
/**
* Fetch data from NetSuite and add it to the queue.
*
* @return void
*/
public function fetchDataToQueue();
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
public function convertToMagentoFormat($netSuiteData);
}
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Block\Adminhtml\Location\Edit;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class BackButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Back'),
'on_click' => sprintf("location.href = '%s';", $this->getBackUrl()),
'class' => 'back',
'sort_order' => 10
];
}
/**
* Get URL for back (reset) button
*
* @return string
*/
public function getBackUrl()
{
return $this->getUrl('*/*/');
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Block\Adminhtml\Location\Edit;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class DeleteButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
$data = [];
if ($this->getModelId()) {
$data = [
'label' => __('Delete Location'),
'class' => 'delete',
'on_click' => 'deleteConfirm(\'' . __(
'Are you sure you want to do this?'
) . '\', \'' . $this->getDeleteUrl() . '\')',
'sort_order' => 20,
];
}
return $data;
}
/**
* Get URL for delete button
*
* @return string
*/
public function getDeleteUrl()
{
return $this->getUrl('*/*/delete', ['location_id' => $this->getModelId()]);
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Block\Adminhtml\Location\Edit;
use Magento\Backend\Block\Widget\Context;
abstract class GenericButton
{
protected $context;
/**
* @param \Magento\Backend\Block\Widget\Context $context
*/
public function __construct(Context $context)
{
$this->context = $context;
}
/**
* Return model ID
*
* @return int|null
*/
public function getModelId()
{
return $this->context->getRequest()->getParam('location_id');
}
/**
* Generate url by route and parameters
*
* @param string $route
* @param array $params
* @return string
*/
public function getUrl($route = '', $params = [])
{
return $this->context->getUrlBuilder()->getUrl($route, $params);
}
}
@@ -0,0 +1,31 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Block\Adminhtml\Location\Edit;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class SaveAndContinueButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Save and Continue Edit'),
'class' => 'save',
'data_attribute' => [
'mage-init' => [
'button' => ['event' => 'saveAndContinueEdit'],
],
],
'sort_order' => 80,
];
}
}
@@ -0,0 +1,30 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Block\Adminhtml\Location\Edit;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class SaveButton extends GenericButton implements ButtonProviderInterface
{
/**
* @return array
*/
public function getButtonData()
{
return [
'label' => __('Save Location'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'save']],
'form-role' => 'save',
],
'sort_order' => 90,
];
}
}
@@ -0,0 +1,58 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
class CustomerQueue extends Action
{
protected $_coreRegistry;
const ADMIN_RESOURCE = 'JR_NetSuite::top_level';
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry
) {
$this->_coreRegistry = $coreRegistry;
parent::__construct($context);
}
/**
* Execute Action
*
* @return void
*/
public function execute()
{
$doNothing = true;
}
/**
* Init page
*
* @param \Magento\Backend\Model\View\Result\Page $resultPage
* @return \Magento\Backend\Model\View\Result\Page
*/
public function initPage($resultPage)
{
$resultPage->setActiveMenu(self::ADMIN_RESOURCE)
->addBreadcrumb(__('NetSuite'), __('NetSuite'))
->addBreadcrumb(__('Customer Queue'), __('Customer Queue'));
return $resultPage;
}
/**
* @inheritdoc
*/
protected function _isAllowed()
{
return $this->_authorization
->isAllowed(
'JR_NetSuite::customerueue'
);
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\CustomerQueue;
class Delete extends \JR\NetSuite\Controller\Adminhtml\CustomerQueue
{
/**
* Delete action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
// check if we know what should be deleted
$id = $this->getRequest()->getParam('location_id');
if ($id) {
try {
// init model and delete
$model = $this->_objectManager->create(\JR\NetSuite\Model\CustomerQueue::class);
$model->load($id);
$model->delete();
// display success message
$this->messageManager->addSuccessMessage(__('You deleted the CustomerQueue.'));
// go to grid
return $resultRedirect->setPath('*/*/');
} catch (\Exception $e) {
// display error message
$this->messageManager->addErrorMessage($e->getMessage());
// go back to edit form
return $resultRedirect->setPath('*/*/edit', ['location_id' => $id]);
}
}
// display error message
$this->messageManager->addErrorMessage(__('We can\'t find a CustomerQueue to delete.'));
// go to grid
return $resultRedirect->setPath('*/*/');
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\CustomerQueue;
class Edit extends \JR\NetSuite\Controller\Adminhtml\CustomerQueue
{
protected $resultPageFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context, $coreRegistry);
}
/**
* Edit action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
// 1. Get ID and create model
$id = $this->getRequest()->getParam('customer_queue_id');
$model = $this->_objectManager->create(\JR\NetSuite\Model\CustomerQueue::class);
// 2. Initial checking
if ($id) {
$model->load($id);
if (!$model->getId()) {
$this->messageManager->addErrorMessage(__('This CustomerQueue no longer exists.'));
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/');
}
}
$this->_coreRegistry->register('jr_netsuite_customer_queue', $model);
// 3. Build edit form
/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$this->initPage($resultPage)->addBreadcrumb(
$id ? __('Edit CustomerQueue') : __('New CustomerQueue'),
$id ? __('Edit CustomerQueue') : __('New CustomerQueue')
);
$resultPage->getConfig()->getTitle()->prepend(__('CustomerQueues'));
$resultPage->getConfig()->getTitle()->prepend($model->getId() ? __('Edit CustomerQueue %1', $model->getId()) : __('New CustomerQueue'));
return $resultPage;
}
}
@@ -0,0 +1,54 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\CustomerQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use JR\NetSuite\Queue\CustomerQueueManager;
use JR\NetSuite\Controller\Adminhtml\CustomerQueue;
/**
* Class Fetch from controller
*/
class Fetch extends CustomerQueue
{
const MENU_ID = 'JR_NetSuite::customerqueue';
protected $resultPageFactory;
/**
* @var CustomerQueueManager
*/
protected $customerQueueManager;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
CustomerQueueManager $customerQueueManager
) {
$this->resultPageFactory = $resultPageFactory;
$this->customerQueueManager = $customerQueueManager;
parent::__construct($context, $coreRegistry);
}
public function execute()
{
$result = $this->customerQueueManager->fetchAndEnqueue(true);
if ($result['error']) {
$this->messageManager->addErrorMessage(__('Error while fetching data from NetSuite. ' . $result['message']));
} else {
$this->messageManager->addSuccessMessage(__('Data fetched successfully. ' . $result['message']));
}
$this->_redirect('jr_netsuite/customerqueue/index');
}
/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(static::MENU_ID);
}
}
@@ -0,0 +1,67 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\CustomerQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use JR\NetSuite\Cron\CustomerSyncCron;
/**
* Class ClearHistory from controller
*/
class Import extends \Magento\Backend\App\Action
{
const MENU_ID = 'JR_NetSuite::customerqueue';
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @var CustomerSyncCron
*/
protected $customerSyncCron;
/**
* @var \Magento\Framework\App\ResourceConnection
*/
protected $_resource;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
CustomerSyncCron $customerSyncCron
) {
$this->_resource = $resource;
$this->resultPageFactory = $resultPageFactory;
$this->customerSyncCron = $customerSyncCron;
parent::__construct($context);
}
public function execute()
{
try {
$processed = 0;
do {
$count = $this->customerSyncCron->processQueueItems();
if ($count) {
$processed += $count;
}
} while ($count);
$this->messageManager->addSuccessMessage(__('A total of %1 customers imported.', $processed));
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
$this->_redirect('jr_netsuite/customerqueue/index');
}
/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(static::MENU_ID);
}
}
@@ -0,0 +1,45 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\CustomerQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\Page;
use JR\NetSuite\Controller\Adminhtml\CustomerQueue;
class Index extends CustomerQueue
{
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
private $resultPageFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context, $coreRegistry);
}
/**
* Load the page defined in view/adminhtml/layout/jr_netsuite_customer_queue_index.xml
*
* @return Page
*/
public function execute()
{
/** @var Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->setActiveMenu('JR_NetSuite::customerqueue');
$resultPage->getConfig()->getTitle()->prepend(__('Customer Queue'));
return $resultPage;
}
}
@@ -0,0 +1,64 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\CustomerQueue;
class InlineEdit extends \Magento\Backend\App\Action
{
protected $jsonFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $jsonFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $jsonFactory
) {
parent::__construct($context);
$this->jsonFactory = $jsonFactory;
}
/**
* Inline edit action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
/** @var \Magento\Framework\Controller\Result\Json $resultJson */
$resultJson = $this->jsonFactory->create();
$error = false;
$messages = [];
if ($this->getRequest()->getParam('isAjax')) {
$postItems = $this->getRequest()->getParam('items', []);
if (!count($postItems)) {
$messages[] = __('Please correct the data sent.');
$error = true;
} else {
foreach (array_keys($postItems) as $modelid) {
/** @var \JR\NetSuite\Model\CustomerQueue $model */
$model = $this->_objectManager->create(\JR\NetSuite\Model\CustomerQueue::class)->load($modelid);
try {
$model->setData(array_merge($model->getData(), $postItems[$modelid]));
$model->save();
} catch (\Exception $e) {
$messages[] = "[Customer Queue ID: {$modelid}] {$e->getMessage()}";
$error = true;
}
}
}
}
return $resultJson->setData([
'messages' => $messages,
'error' => $error
]);
}
}
@@ -0,0 +1,70 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\CustomerQueue;
use Magento\Framework\Exception\LocalizedException;
class Save extends \Magento\Backend\App\Action
{
protected $dataPersistor;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
) {
$this->dataPersistor = $dataPersistor;
parent::__construct($context);
}
/**
* Save action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$data = $this->getRequest()->getPostValue();
if ($data) {
$id = $this->getRequest()->getParam('customer_queue_id');
$model = $this->_objectManager->create(\JR\NetSuite\Model\CustomerQueue::class)->load($id);
if (!$model->getId() && $id) {
$this->messageManager->addErrorMessage(__('This Customer Queue no longer exists.'));
return $resultRedirect->setPath('*/*/');
}
$model->setData($data);
try {
$model->save();
$this->messageManager->addSuccessMessage(__('You saved the Customer Queue.'));
$this->dataPersistor->clear('jr_netsuite_customer_queue');
if ($this->getRequest()->getParam('back')) {
return $resultRedirect->setPath('*/*/edit', ['customer_queue_id' => $model->getId()]);
}
return $resultRedirect->setPath('*/*/');
} catch (LocalizedException $e) {
$this->messageManager->addErrorMessage($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the Customer Queue.'));
}
$this->dataPersistor->set('jr_netsuite_customer_queue', $data);
return $resultRedirect->setPath('*/*/edit', ['customer_queue_id' => $this->getRequest()->getParam('customer_queue_id')]);
}
return $resultRedirect->setPath('*/*/');
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
class Location extends Action
{
protected $_coreRegistry;
const ADMIN_RESOURCE = 'JR_NetSuite::top_level';
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry
) {
$this->_coreRegistry = $coreRegistry;
parent::__construct($context);
}
/**
* Execute Action
*
* @return void
*/
public function execute()
{
$doNothing = true;
}
/**
* Init page
*
* @param \Magento\Backend\Model\View\Result\Page $resultPage
* @return \Magento\Backend\Model\View\Result\Page
*/
public function initPage($resultPage)
{
$resultPage->setActiveMenu(self::ADMIN_RESOURCE)
->addBreadcrumb(__('NetSuite'), __('NetSuite'))
->addBreadcrumb(__('Location'), __('Location'));
return $resultPage;
}
/**
* @inheritdoc
*/
protected function _isAllowed()
{
return $this->_authorization
->isAllowed(
'JR_NetSuite::location'
);
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\Location;
class Delete extends \JR\NetSuite\Controller\Adminhtml\Location
{
/**
* Delete action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
// check if we know what should be deleted
$id = $this->getRequest()->getParam('location_id');
if ($id) {
try {
// init model and delete
$model = $this->_objectManager->create(\JR\NetSuite\Model\Location::class);
$model->load($id);
$model->delete();
// display success message
$this->messageManager->addSuccessMessage(__('You deleted the Location.'));
// go to grid
return $resultRedirect->setPath('*/*/');
} catch (\Exception $e) {
// display error message
$this->messageManager->addErrorMessage($e->getMessage());
// go back to edit form
return $resultRedirect->setPath('*/*/edit', ['location_id' => $id]);
}
}
// display error message
$this->messageManager->addErrorMessage(__('We can\'t find a Location to delete.'));
// go to grid
return $resultRedirect->setPath('*/*/');
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\Location;
class Edit extends \JR\NetSuite\Controller\Adminhtml\Location
{
protected $resultPageFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context, $coreRegistry);
}
/**
* Edit action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
// 1. Get ID and create model
$id = $this->getRequest()->getParam('location_id');
$model = $this->_objectManager->create(\JR\NetSuite\Model\Location::class);
// 2. Initial checking
if ($id) {
$model->load($id);
if (!$model->getId()) {
$this->messageManager->addErrorMessage(__('This Location no longer exists.'));
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/');
}
}
$this->_coreRegistry->register('jr_netsuite_location', $model);
// 3. Build edit form
/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$this->initPage($resultPage)->addBreadcrumb(
$id ? __('Edit Location') : __('New Location'),
$id ? __('Edit Location') : __('New Location')
);
$resultPage->getConfig()->getTitle()->prepend(__('Locations'));
$resultPage->getConfig()->getTitle()->prepend($model->getId() ? __('Edit Location %1', $model->getId()) : __('New Location'));
return $resultPage;
}
}
@@ -0,0 +1,54 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\Location;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use JR\NetSuite\Service\LocationsSyncService;
use JR\NetSuite\Controller\Adminhtml\Location;
/**
* Class Fetch from controller
*/
class Fetch extends Location
{
const MENU_ID = 'JR_NetSuite::location';
protected $resultPageFactory;
/**
* @var LocationsSyncService
*/
protected $locationsSyncService;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
LocationsSyncService $locationsSyncService
) {
$this->resultPageFactory = $resultPageFactory;
$this->locationsSyncService = $locationsSyncService;
parent::__construct($context, $coreRegistry);
}
public function execute()
{
$result = $this->locationsSyncService->sync();
if ($result['error']) {
$this->messageManager->addErrorMessage(__('Error while fetching data from NetSuite. ' . $result['message']));
} else {
$this->messageManager->addSuccessMessage(__('Data fetched successfully. ' . $result['message']));
}
$this->_redirect('jr_netsuite/location/index');
}
/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(static::MENU_ID);
}
}
@@ -0,0 +1,45 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\Location;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\Page;
use JR\NetSuite\Controller\Adminhtml\Location;
class Index extends Location
{
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
private $resultPageFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context, $coreRegistry);
}
/**
* Load the page defined in view/adminhtml/layout/jr_netsuite_location_index.xml
*
* @return Page
*/
public function execute()
{
/** @var Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->setActiveMenu('JR_NetSuite::location');
$resultPage->getConfig()->getTitle()->prepend(__('Locations'));
return $resultPage;
}
}
@@ -0,0 +1,64 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\Location;
class InlineEdit extends \Magento\Backend\App\Action
{
protected $jsonFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $jsonFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $jsonFactory
) {
parent::__construct($context);
$this->jsonFactory = $jsonFactory;
}
/**
* Inline edit action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
/** @var \Magento\Framework\Controller\Result\Json $resultJson */
$resultJson = $this->jsonFactory->create();
$error = false;
$messages = [];
if ($this->getRequest()->getParam('isAjax')) {
$postItems = $this->getRequest()->getParam('items', []);
if (!count($postItems)) {
$messages[] = __('Please correct the data sent.');
$error = true;
} else {
foreach (array_keys($postItems) as $modelid) {
/** @var \JR\NetSuite\Model\Location $model */
$model = $this->_objectManager->create(\JR\NetSuite\Model\Location::class)->load($modelid);
try {
$model->setData(array_merge($model->getData(), $postItems[$modelid]));
$model->save();
} catch (\Exception $e) {
$messages[] = "[Location ID: {$modelid}] {$e->getMessage()}";
$error = true;
}
}
}
}
return $resultJson->setData([
'messages' => $messages,
'error' => $error
]);
}
}
@@ -0,0 +1,70 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\Location;
use Magento\Framework\Exception\LocalizedException;
class Save extends \Magento\Backend\App\Action
{
protected $dataPersistor;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
) {
$this->dataPersistor = $dataPersistor;
parent::__construct($context);
}
/**
* Save action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$data = $this->getRequest()->getPostValue();
if ($data) {
$id = $this->getRequest()->getParam('location_id');
$model = $this->_objectManager->create(\JR\NetSuite\Model\Location::class)->load($id);
if (!$model->getId() && $id) {
$this->messageManager->addErrorMessage(__('This Location no longer exists.'));
return $resultRedirect->setPath('*/*/');
}
$model->setData($data);
try {
$model->save();
$this->messageManager->addSuccessMessage(__('You saved the Location.'));
$this->dataPersistor->clear('jr_netsuite_location');
if ($this->getRequest()->getParam('back')) {
return $resultRedirect->setPath('*/*/edit', ['location_id' => $model->getId()]);
}
return $resultRedirect->setPath('*/*/');
} catch (LocalizedException $e) {
$this->messageManager->addErrorMessage($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the Location.'));
}
$this->dataPersistor->set('jr_netsuite_location', $data);
return $resultRedirect->setPath('*/*/edit', ['location_id' => $this->getRequest()->getParam('location_id')]);
}
return $resultRedirect->setPath('*/*/');
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
class OrderQueue extends Action
{
protected $_coreRegistry;
const ADMIN_RESOURCE = 'JR_NetSuite::top_level';
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry
) {
$this->_coreRegistry = $coreRegistry;
parent::__construct($context);
}
/**
* Execute Action
*
* @return void
*/
public function execute()
{
$doNothing = true;
}
/**
* Init page
*
* @param \Magento\Backend\Model\View\Result\Page $resultPage
* @return \Magento\Backend\Model\View\Result\Page
*/
public function initPage($resultPage)
{
$resultPage->setActiveMenu(self::ADMIN_RESOURCE)
->addBreadcrumb(__('NetSuite'), __('NetSuite'))
->addBreadcrumb(__('Order Queue'), __('Order Queue'));
return $resultPage;
}
/**
* @inheritdoc
*/
protected function _isAllowed()
{
return $this->_authorization
->isAllowed(
'JR_NetSuite::orderqueue'
);
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\OrderQueue;
class Delete extends \JR\NetSuite\Controller\Adminhtml\OrderQueue
{
/**
* Delete action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
// check if we know what should be deleted
$id = $this->getRequest()->getParam('location_id');
if ($id) {
try {
// init model and delete
$model = $this->_objectManager->create(\JR\NetSuite\Model\OrderQueue::class);
$model->load($id);
$model->delete();
// display success message
$this->messageManager->addSuccessMessage(__('You deleted the OrderQueue.'));
// go to grid
return $resultRedirect->setPath('*/*/');
} catch (\Exception $e) {
// display error message
$this->messageManager->addErrorMessage($e->getMessage());
// go back to edit form
return $resultRedirect->setPath('*/*/edit', ['location_id' => $id]);
}
}
// display error message
$this->messageManager->addErrorMessage(__('We can\'t find a OrderQueue to delete.'));
// go to grid
return $resultRedirect->setPath('*/*/');
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\OrderQueue;
class Edit extends \JR\NetSuite\Controller\Adminhtml\OrderQueue
{
protected $resultPageFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context, $coreRegistry);
}
/**
* Edit action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
// 1. Get ID and create model
$id = $this->getRequest()->getParam('order_queue_id');
$model = $this->_objectManager->create(\JR\NetSuite\Model\OrderQueue::class);
// 2. Initial checking
if ($id) {
$model->load($id);
if (!$model->getId()) {
$this->messageManager->addErrorMessage(__('This OrderQueue no longer exists.'));
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/');
}
}
$this->_coreRegistry->register('jr_netsuite_order_queue', $model);
// 3. Build edit form
/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$this->initPage($resultPage)->addBreadcrumb(
$id ? __('Edit OrderQueue') : __('New OrderQueue'),
$id ? __('Edit OrderQueue') : __('New OrderQueue')
);
$resultPage->getConfig()->getTitle()->prepend(__('OrderQueues'));
$resultPage->getConfig()->getTitle()->prepend($model->getId() ? __('Edit OrderQueue %1', $model->getId()) : __('New OrderQueue'));
return $resultPage;
}
}
@@ -0,0 +1,54 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\OrderQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use JR\NetSuite\Queue\OrderQueueManager;
use JR\NetSuite\Controller\Adminhtml\OrderQueue;
/**
* Class Fetch from controller
*/
class Fetch extends OrderQueue {
const MENU_ID = 'JR_NetSuite::orderqueue';
protected $resultPageFactory;
/**
* @var OrderQueueManager
*/
protected $orderQueueManager;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
OrderQueueManager $orderQueueManager
) {
$this->resultPageFactory = $resultPageFactory;
$this->orderQueueManager = $orderQueueManager;
parent::__construct($context, $coreRegistry);
}
public function execute() {
$result = $this->orderQueueManager->fetchAndEnqueue();
if ($result['error']) {
$this->messageManager->addErrorMessage(__('Error while fetching data from NetSuite. ' . $result['message']));
} else {
$this->messageManager->addSuccessMessage(__('Data fetched successfully. ' . $result['message']));
}
$this->_redirect('jr_netsuite/orderqueue/index');
}
/**
* @return bool
*/
protected function _isAllowed() {
return $this->_authorization->isAllowed(static::MENU_ID);
}
}
@@ -0,0 +1,67 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\OrderQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use JR\NetSuite\Cron\OrderSyncCron;
/**
* Class ClearHistory from controller
*/
class Import extends \Magento\Backend\App\Action
{
const MENU_ID = 'JR_NetSuite::orderqueue';
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @var OrderSyncCron
*/
protected $orderSyncCron;
/**
* @var \Magento\Framework\App\ResourceConnection
*/
protected $_resource;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
OrderSyncCron $orderSyncCron
) {
$this->_resource = $resource;
$this->resultPageFactory = $resultPageFactory;
$this->orderSyncCron = $orderSyncCron;
parent::__construct($context);
}
public function execute()
{
try {
$processed = 0;
// do {
$count = $this->orderSyncCron->processQueueItems();
if ($count) {
$processed += $count;
}
// } while ($count);
$this->messageManager->addSuccessMessage(__('A total of %1 orders imported.', $processed));
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
$this->_redirect('jr_netsuite/orderqueue/index');
}
/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(static::MENU_ID);
}
}
@@ -0,0 +1,45 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\OrderQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\Page;
use JR\NetSuite\Controller\Adminhtml\OrderQueue;
class Index extends OrderQueue
{
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
private $resultPageFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context, $coreRegistry);
}
/**
* Load the page defined in view/adminhtml/layout/jr_netsuite_order_queue_index.xml
*
* @return Page
*/
public function execute()
{
/** @var Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->setActiveMenu('JR_NetSuite::orderqueue');
$resultPage->getConfig()->getTitle()->prepend(__('Order Queue'));
return $resultPage;
}
}
@@ -0,0 +1,64 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\OrderQueue;
class InlineEdit extends \Magento\Backend\App\Action
{
protected $jsonFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $jsonFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $jsonFactory
) {
parent::__construct($context);
$this->jsonFactory = $jsonFactory;
}
/**
* Inline edit action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
/** @var \Magento\Framework\Controller\Result\Json $resultJson */
$resultJson = $this->jsonFactory->create();
$error = false;
$messages = [];
if ($this->getRequest()->getParam('isAjax')) {
$postItems = $this->getRequest()->getParam('items', []);
if (!count($postItems)) {
$messages[] = __('Please correct the data sent.');
$error = true;
} else {
foreach (array_keys($postItems) as $modelid) {
/** @var \JR\NetSuite\Model\OrderQueue $model */
$model = $this->_objectManager->create(\JR\NetSuite\Model\OrderQueue::class)->load($modelid);
try {
$model->setData(array_merge($model->getData(), $postItems[$modelid]));
$model->save();
} catch (\Exception $e) {
$messages[] = "[Order Queue ID: {$modelid}] {$e->getMessage()}";
$error = true;
}
}
}
}
return $resultJson->setData([
'messages' => $messages,
'error' => $error
]);
}
}
@@ -0,0 +1,70 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Controller\Adminhtml\OrderQueue;
use Magento\Framework\Exception\LocalizedException;
class Save extends \Magento\Backend\App\Action
{
protected $dataPersistor;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
) {
$this->dataPersistor = $dataPersistor;
parent::__construct($context);
}
/**
* Save action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$data = $this->getRequest()->getPostValue();
if ($data) {
$id = $this->getRequest()->getParam('order_queue_id');
$model = $this->_objectManager->create(\JR\NetSuite\Model\OrderQueue::class)->load($id);
if (!$model->getId() && $id) {
$this->messageManager->addErrorMessage(__('This Order Queue no longer exists.'));
return $resultRedirect->setPath('*/*/');
}
$model->setData($data);
try {
$model->save();
$this->messageManager->addSuccessMessage(__('You saved the Order Queue.'));
$this->dataPersistor->clear('jr_netsuite_order_queue');
if ($this->getRequest()->getParam('back')) {
return $resultRedirect->setPath('*/*/edit', ['order_queue_id' => $model->getId()]);
}
return $resultRedirect->setPath('*/*/');
} catch (LocalizedException $e) {
$this->messageManager->addErrorMessage($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the Order Queue.'));
}
$this->dataPersistor->set('jr_netsuite_order_queue', $data);
return $resultRedirect->setPath('*/*/edit', ['order_queue_id' => $this->getRequest()->getParam('order_queue_id')]);
}
return $resultRedirect->setPath('*/*/');
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
class ProductQueue extends Action
{
/**
* Execute Action
*
* @return void
*/
public function execute()
{
$doNothing = true;
}
/**
* @inheritdoc
*/
protected function _isAllowed()
{
return $this->_authorization
->isAllowed(
'JR_NetSuite::productqueue'
);
}
}
@@ -0,0 +1,52 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\ProductQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use JR\NetSuite\Queue\ProductQueueManager;
/**
* Class ClearHistory from controller
*/
class Fetch extends \Magento\Backend\App\Action
{
const MENU_ID = 'JR_NetSuite::productqueue';
protected $resultPageFactory;
/**
* @var ProductQueueManager
*/
protected $productQueueManager;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
ProductQueueManager $productQueueManager
) {
$this->resultPageFactory = $resultPageFactory;
$this->productQueueManager = $productQueueManager;
parent::__construct($context);
}
public function execute()
{
$result = $this->productQueueManager->fetchAndEnqueue(true);
if ($result['error']) {
$this->messageManager->addErrorMessage(__('Error while fetching data from NetSuite. ' . $result['message']));
} else {
$this->messageManager->addSuccessMessage(__('Data fetched successfully. ' . $result['message']));
}
$this->_redirect('jr_netsuite/productqueue/index');
}
/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(static::MENU_ID);
}
}
@@ -0,0 +1,69 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\ProductQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use JR\NetSuite\Cron\ProductSyncCron;
/**
* Class ClearHistory from controller
*/
class Import extends \Magento\Backend\App\Action
{
const MENU_ID = 'JR_NetSuite::productqueue';
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @var ProductSyncCron
*/
protected $productSyncCron;
/**
* @var \Magento\Framework\App\ResourceConnection
*/
protected $_resource;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
ProductSyncCron $productSyncCron
) {
$this->_resource = $resource;
$this->resultPageFactory = $resultPageFactory;
$this->productSyncCron = $productSyncCron;
parent::__construct($context);
}
public function execute()
{
try {
$processed = 0;
$loopCount = 0;
do {
$count = $this->productSyncCron->processQueueItems();
if ($count) {
$processed += $count;
}
$loopCount++;
} while ($count);
$this->messageManager->addSuccessMessage(__('A total of %1 product queues processed.', $processed));
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
$this->_redirect('jr_netsuite/productqueue/index');
}
/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(static::MENU_ID);
}
}
@@ -0,0 +1,43 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\ProductQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\Page;
use JR\NetSuite\Controller\Adminhtml\ProductQueue;
class Index extends ProductQueue
{
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
private $resultPageFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
PageFactory $resultPageFactory
) {
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
/**
* Load the page defined in view/adminhtml/layout/jr_netsuite_productqueue_index.xml
*
* @return Page
*/
public function execute()
{
/** @var Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->setActiveMenu('JR_NetSuite::productqueue');
$resultPage->getConfig()->getTitle()->prepend(__('Product Queue'));
return $resultPage;
}
}
@@ -0,0 +1,73 @@
<?php
/**
* @category JR
* @package JR_NetSuite
* @author JR Software Private Limited
* @copyright Copyright (c) JR Software Private Limited (https://JR.com)
* @license https://store.JR.com/license.html
*/
namespace JR\NetSuite\Controller\Adminhtml\ProductQueue;
use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use JR\NetSuite\Model\ResourceModel\ProductQueue\CollectionFactory;
class MassDelete extends \Magento\Backend\App\Action
{
/**
* Massactions filter.
*
* @var Filter
*/
private $filter;
/**
* @var CollectionFactory
*/
private $collectionFactory;
/**
* @param Context $context
* @param Filter $filter
* @param CollectionFactory $collectionFactory
*/
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory
) {
$this->filter = $filter;
$this->collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Execute action
*
* @return \Magento\Backend\Model\View\Result\Redirect
*/
public function execute()
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
$accountsCount = 0;
foreach ($collection->getItems() as $account) {
$this->deleteObj($account);
++$accountsCount;
}
$this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', $accountsCount));
return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/index');
}
/**
* Delete object.
*
* @param mixed $object
* @return void
*/
private function deleteObj($object)
{
$object->delete();
}
}
@@ -0,0 +1,64 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\ProductQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use JR\NetSuite\Cron\ProductSyncCron;
/**
* Class ClearHistory from controller
*/
class Schedule extends \Magento\Backend\App\Action
{
const MENU_ID = 'JR_NetSuite::productqueue';
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @var ProductSyncCron
*/
protected $productSyncCron;
/**
* @var \Magento\Framework\App\ResourceConnection
*/
protected $_resource;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
ProductSyncCron $productSyncCron
) {
$this->_resource = $resource;
$this->resultPageFactory = $resultPageFactory;
$this->productSyncCron = $productSyncCron;
parent::__construct($context);
}
public function execute()
{
try {
$result = $this->productSyncCron->scheduleCronJob();
if (!$result) {
throw new \Exception('Cron job could not be scheduled.');
}
$this->messageManager->addSuccessMessage(__('Cron job created successfully. Please wait for the product to be imported.'));
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
$this->_redirect('jr_netsuite/productqueue/index');
}
/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(static::MENU_ID);
}
}
@@ -0,0 +1,76 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\ProductQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\Page;
use JR\NetSuite\Model\ResourceModel\ProductQueueFactory;
/**
* Class ViewJson
*/
class View extends \Magento\Backend\App\Action
{
const MENU_ID = 'JR_NetSuite::productqueue';
/**
* @var PageFactory
*/
protected $resultPageFactory = false;
/**
* @var ProductQueueFactory
*/
protected $productQueueFactory;
/**
* Index constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
ProductQueueFactory $productQueueFactory
) {
parent::__construct($context);
$this->productQueueFactory = $productQueueFactory;
}
/**
* Load the page defined in json form
*
* @return Page
*/
public function execute()
{
$entity_id = $this->getRequest()->getParam('entity_id');
if ($entity_id > 0) {
$prductQueue = $this->productQueueFactory->create()->load($entity_id);
if ($prductQueue) {
$resJson = $prductQueue->getData('data');
header('Content-Type: application/json');
http_response_code(200);
exit($resJson);
}
}
$this->messageManager->addErrorMessage(__('No record found!'));
$this->_redirect('jrnetsuite/productqueue/index');
}
/**
* Allow modules
*
* @return int
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('JR_NetSuite::product_queue');
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
class RmaQueue extends Action
{
/**
* Execute Action
*
* @return void
*/
public function execute()
{
$doNothing = true;
}
/**
* @inheritdoc
*/
protected function _isAllowed()
{
return $this->_authorization
->isAllowed(
'JR_NetSuite::rmaqueue'
);
}
}
@@ -0,0 +1,52 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\RmaQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use JR\NetSuite\Queue\RmaQueueManager;
/**
* Class ClearHistory from controller
*/
class Fetch extends \Magento\Backend\App\Action
{
const MENU_ID = 'JR_NetSuite::rmaqueue';
protected $resultPageFactory;
/**
* @var RmaQueueManager
*/
protected $rmaQueueManager;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
RmaQueueManager $rmaQueueManager
) {
$this->resultPageFactory = $resultPageFactory;
$this->rmaQueueManager = $rmaQueueManager;
parent::__construct($context);
}
public function execute()
{
$result = $this->rmaQueueManager->fetchAndEnqueue();
if ($result['error']) {
$this->messageManager->addErrorMessage(__('Error while fetching data from NetSuite. ' . $result['message']));
} else {
$this->messageManager->addSuccessMessage(__('Data fetched successfully. ' . $result['message']));
}
$this->_redirect('jr_netsuite/rmaqueue/index');
}
/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(static::MENU_ID);
}
}
@@ -0,0 +1,67 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\RmaQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use JR\NetSuite\Cron\RmaSyncCron;
/**
* Class ClearHistory from controller
*/
class Import extends \Magento\Backend\App\Action
{
const MENU_ID = 'JR_NetSuite::rmaqueue';
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @var RmaSyncCron
*/
protected $rmaSyncCron;
/**
* @var \Magento\Framework\App\ResourceConnection
*/
protected $_resource;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
RmaSyncCron $rmaSyncCron
) {
$this->_resource = $resource;
$this->resultPageFactory = $resultPageFactory;
$this->rmaSyncCron = $rmaSyncCron;
parent::__construct($context);
}
public function execute()
{
try {
$processed = 0;
// do {
$count = $this->rmaSyncCron->processQueueItems();
if ($count) {
$processed += $count;
}
// } while ($count);
$this->messageManager->addSuccessMessage(__('A total of %1 rmas imported.', $processed));
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
$this->_redirect('jr_netsuite/rmaqueue/index');
}
/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed(static::MENU_ID);
}
}
@@ -0,0 +1,43 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\RmaQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\Page;
use JR\NetSuite\Controller\Adminhtml\RmaQueue;
class Index extends RmaQueue
{
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
private $resultPageFactory;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
PageFactory $resultPageFactory
) {
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
/**
* Load the page defined in view/adminhtml/layout/jr_netsuite_rmaqueue_index.xml
*
* @return Page
*/
public function execute()
{
/** @var Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->setActiveMenu('JR_NetSuite::rmaqueue');
$resultPage->getConfig()->getTitle()->prepend(__('RMA Queue'));
return $resultPage;
}
}
@@ -0,0 +1,73 @@
<?php
/**
* @category JR
* @package JR_NetSuite
* @author JR Software Private Limited
* @copyright Copyright (c) JR Software Private Limited (https://JR.com)
* @license https://store.JR.com/license.html
*/
namespace JR\NetSuite\Controller\Adminhtml\RmaQueue;
use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use JR\NetSuite\Model\ResourceModel\RmaQueue\CollectionFactory;
class MassDelete extends \Magento\Backend\App\Action
{
/**
* Massactions filter.
*
* @var Filter
*/
private $filter;
/**
* @var CollectionFactory
*/
private $collectionFactory;
/**
* @param Context $context
* @param Filter $filter
* @param CollectionFactory $collectionFactory
*/
public function __construct(
Context $context,
Filter $filter,
CollectionFactory $collectionFactory
) {
$this->filter = $filter;
$this->collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Execute action
*
* @return \Magento\Backend\Model\View\Result\Redirect
*/
public function execute()
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
$accountsCount = 0;
foreach ($collection->getItems() as $account) {
$this->deleteObj($account);
++$accountsCount;
}
$this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', $accountsCount));
return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/index');
}
/**
* Delete object.
*
* @param mixed $object
* @return void
*/
private function deleteObj($object)
{
$object->delete();
}
}
@@ -0,0 +1,76 @@
<?php
namespace JR\NetSuite\Controller\Adminhtml\RmaQueue;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\Page;
use JR\NetSuite\Model\ResourceModel\RmaQueueFactory;
/**
* Class ViewJson
*/
class View extends \Magento\Backend\App\Action
{
const MENU_ID = 'JR_NetSuite::rmaqueue';
/**
* @var PageFactory
*/
protected $resultPageFactory = false;
/**
* @var RmaQueueFactory
*/
protected $rmaQueueFactory;
/**
* Index constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
RmaQueueFactory $rmaQueueFactory
) {
parent::__construct($context);
$this->rmaQueueFactory = $rmaQueueFactory;
}
/**
* Load the page defined in json form
*
* @return Page
*/
public function execute()
{
$entity_id = $this->getRequest()->getParam('entity_id');
if ($entity_id > 0) {
$prductQueue = $this->rmaQueueFactory->create()->load($entity_id);
if ($prductQueue) {
$resJson = $prductQueue->getData('data');
header('Content-Type: application/json');
http_response_code(200);
exit($resJson);
}
}
$this->messageManager->addErrorMessage(__('No record found!'));
$this->_redirect('jrnetsuite/rmaqueue/index');
}
/**
* Allow modules
*
* @return int
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('JR_NetSuite::rma_queue');
}
}
+174
View File
@@ -0,0 +1,174 @@
<?php
namespace JR\NetSuite\Cron;
use Magento\Cron\Model\Schedule;
abstract class AbstractSyncCron {
public const FETCH = 'fetch';
public const PROCESS = 'process';
/**
* @var int
*/
private $processed = 0;
/**
* @var \JR\NetSuite\Helper\Data
*/
protected $helper;
/**
* @var \JR\NetSuite\Logger\Logger
*/
protected $logger;
/**
* @var \Magento\Cron\Model\ScheduleFactory
*/
protected $scheduleFactory;
/**
* @var \Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory
*/
protected $scheduleCollectionFactory;
/**
* AbstractSyncCron constructor.
*
* @param \Magento\Cron\Model\ScheduleFactory $scheduleFactory
* @param \Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory
* @param \JR\NetSuite\Helper\Data $helper
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
) {
$this->helper = $helper;
$this->scheduleFactory = $scheduleFactory;
$this->scheduleCollectionFactory = $scheduleCollectionFactory;
$this->logger = $helper->getLogger();
}
/**
* get job code
*/
abstract public function getJobCode();
/**
* get queue manager
*/
abstract protected function getQueueManager();
/**
* Execute the cron.
*
* @return void
*/
public function fetchAndEnqueue() {
// $this->logger->info("[$this->JOB_CODE] fetchAndEnqueue");
if (!$this->helper->getNetSuiteIsEnabled() || $this->isRunningCurrently(self::FETCH)) {
$this->processed = 0;
return;
}
$this->getQueueManager()->fetchAndEnqueue();
}
/**
* Execute the cron.
*
* @return void
*/
public function fetchAllAndEnqueue() {
// $this->logger->info("[$this->JOB_CODE] fetchAllAndEnqueue");
if (!$this->helper->getNetSuiteIsEnabled() || $this->isRunningCurrently(self::FETCH)) {
$this->processed = 0;
return;
}
$this->getQueueManager()->fetchAndEnqueue(true);
}
/**
* Schedule the cron.
*
* @param string $time
* @return bool
*/
public function scheduleCronJob($type = self::PROCESS, $time = '+1 minute') {
$currentDateTime = (new \DateTime())->format('Y-m-d H:i:s');
$scheduledDateTime = (new \DateTime())->modify($time)->format('Y-m-d H:i:00');
return $this->scheduleFactory->create()
->setJobCode($this->getJobCode() . '_' . $type)
->setStatus(Schedule::STATUS_PENDING)
->setCreatedAt($currentDateTime)
->setScheduledAt($scheduledDateTime)
->save();
}
// Optionally override in child
protected function getCustomBatchSize(): ?int {
return null; // base class doesn't define custom size
}
/**
* Process the queue items.
*
* @return int
*/
/*
public function processQueueItems()
{
if (!$this->helper->getNetSuiteIsEnabled() || $this->isRunningCurrently(self::PROCESS)) {
$this->processed = 0;
return 0;
}
$batchSize = $this->helper->getCronBatchSize() ?: 50;
return $this->getQueueManager()->processBatch($batchSize);
}
*/
public function processQueueItems() {
if (!$this->helper->getNetSuiteIsEnabled() || $this->isRunningCurrently(self::PROCESS)) {
$this->processed = 0;
return 0;
}
// ?? Let child class override the batch size if needed
$customBatchSize = $this->getCustomBatchSize();
$batchSize = $customBatchSize !== null
? $customBatchSize
: ($this->helper->getCronBatchSize() ?: 50);
$this->logger->info("[$this->JOB_CODE] processQueueItems: batch size -> " . $batchSize);
return $this->getQueueManager()->processBatch($batchSize);
}
/**
* Check if the cron is running currently.
*
* @return bool
*/
public function isRunningCurrently($type = self::PROCESS) {
$schedule = $this->scheduleCollectionFactory->create()
->addFieldToFilter('job_code', $this->getJobCode() . '_' . $type)
->addFieldToFilter('status', Schedule::STATUS_RUNNING);
return $schedule->count() > 1; // 1 meaning the current job
}
/**
* Get the number of processed items.
*
* @return int
*/
public function getProcessed() {
return $this->processed;
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace JR\NetSuite\Cron;
use JR\NetSuite\Queue\CustomerQueueManager;
use Magento\Cron\Model\Schedule;
class CustomerSyncCron extends AbstractSyncCron
{
/**
* @var string
*/
public $JOB_CODE = 'jr_netsuite_sync_customer';
/**
* @var CustomerQueueManager
*/
protected $customerQueueManager;
/**
* CustomerSyncCron constructor.
*
* @param CustomerQueueManager $customerQueueManager
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
CustomerQueueManager $customerQueueManager,
) {
parent::__construct($scheduleFactory, $scheduleCollectionFactory, $helper);
$this->customerQueueManager = $customerQueueManager;
}
/**
* get job code
* @return string
*/
public function getJobCode()
{
return $this->JOB_CODE;
}
/**
* get queue manager
* @return CustomerQueueManager
*/
protected function getQueueManager()
{
return $this->customerQueueManager;
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace JR\NetSuite\Cron;
use JR\NetSuite\Queue\CustomerQueueManager;
use Magento\Cron\Model\Schedule;
class CustomerSyncWorker extends AbstractSyncCron
{
/**
* @var string
*/
public $JOB_CODE = 'jr_netsuite_sync_customer';
/**
* @var CustomerQueueManager
*/
protected $customerQueueManager;
/**
* CustomerSyncWorker constructor.
*
* @param CustomerQueueManager $customerQueueManager
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
CustomerQueueManager $customerQueueManager,
) {
parent::__construct($scheduleFactory, $scheduleCollectionFactory, $helper);
$this->customerQueueManager = $customerQueueManager;
}
/**
* get job code
* @return string
*/
public function getJobCode()
{
return $this->JOB_CODE;
}
/**
* get queue manager
* @return CustomerQueueManager
*/
protected function getQueueManager()
{
return $this->customerQueueManager;
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace JR\NetSuite\Cron;
use JR\NetSuite\Queue\OrderQueueManager;
use Magento\Cron\Model\Schedule;
class OrderSyncCron extends AbstractSyncCron {
/**
* @var string
*/
public $JOB_CODE = 'jr_netsuite_sync_order';
/**
* @var OrderQueueManager
*/
protected $orderQueueManager;
/**
* OrderSyncCron constructor.
* @param \Magento\Cron\Model\ScheduleFactory $scheduleFactory
* @param \Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory
* @param \JR\NetSuite\Helper\Data $helper
* @param OrderQueueManager $orderQueueManager
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
OrderQueueManager $orderQueueManager,
) {
parent::__construct($scheduleFactory, $scheduleCollectionFactory, $helper);
$this->orderQueueManager = $orderQueueManager;
}
/**
* get job code
* @return string
*/
public function getJobCode() {
return $this->JOB_CODE;
}
/**
* get queue manager
* @return OrderQueueManager
*/
protected function getQueueManager() {
return $this->orderQueueManager;
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace JR\NetSuite\Cron;
use JR\NetSuite\Queue\OrderQueueManager;
use Magento\Cron\Model\Schedule;
class OrderSyncWorker extends AbstractSyncCron {
/**
* @var string
*/
public $JOB_CODE = 'jr_netsuite_sync_order';
/**
* @var OrderQueueManager
*/
protected $orderQueueManager;
/**
* OrderSyncCron constructor.
* @param \Magento\Cron\Model\ScheduleFactory $scheduleFactory
* @param \Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory
* @param \JR\NetSuite\Helper\Data $helper
* @param OrderQueueManager $orderQueueManager
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
OrderQueueManager $orderQueueManager,
) {
parent::__construct($scheduleFactory, $scheduleCollectionFactory, $helper);
$this->orderQueueManager = $orderQueueManager;
}
/**
* get job code
* @return string
*/
public function getJobCode() {
return $this->JOB_CODE;
}
/**
* get queue manager
* @return OrderQueueManager
*/
protected function getQueueManager() {
return $this->orderQueueManager;
}
// Custom batch size
protected function getCustomBatchSize(): ?int {
// $this->logger->info("[OrderSyncWorker] getCustomBatchSize");
return 100;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace JR\NetSuite\Cron;
use JR\NetSuite\Queue\ProductQueueManager;
use Magento\Cron\Model\Schedule;
class ProductSyncCron extends AbstractSyncCron
{
/**
* @var string
*/
public $JOB_CODE = 'jr_netsuite_sync_product';
/**
* @var ProductQueueManager
*/
protected $productQueueManager;
/**
* ProductSyncCron constructor.
*
* @param ProductQueueManager $productQueueManager
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
ProductQueueManager $productQueueManager,
) {
parent::__construct($scheduleFactory, $scheduleCollectionFactory, $helper);
$this->productQueueManager = $productQueueManager;
}
/**
* get job code
* @return string
*/
public function getJobCode()
{
return $this->JOB_CODE;
}
/**
* get queue manager
* @return ProductQueueManager
*/
protected function getQueueManager()
{
return $this->productQueueManager;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace JR\NetSuite\Cron;
use JR\NetSuite\Queue\ProductQueueManager;
use Magento\Cron\Model\Schedule;
class ProductSyncWorker extends AbstractSyncCron {
/**
* @var string
*/
public $JOB_CODE = 'jr_netsuite_sync_product';
/**
* @var ProductQueueManager
*/
protected $productQueueManager;
/**
* ProductSyncWorker constructor.
*
* @param ProductQueueManager $productQueueManager
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
ProductQueueManager $productQueueManager,
) {
parent::__construct($scheduleFactory, $scheduleCollectionFactory, $helper);
$this->productQueueManager = $productQueueManager;
}
/**
* get job code
* @return string
*/
public function getJobCode() {
return $this->JOB_CODE;
}
/**
* get queue manager
* @return ProductQueueManager
*/
protected function getQueueManager() {
return $this->productQueueManager;
}
// Custom batch size
protected function getCustomBatchSize(): ?int {
return 100;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace JR\NetSuite\Cron;
use JR\NetSuite\Queue\RmaPushQueueManager;
use Magento\Cron\Model\Schedule;
class RmaPushCron extends AbstractSyncCron
{
/**
* @var string
*/
public $JOB_CODE = 'jr_netsuite_push_rma';
/**
* @var RmaPushQueueManager
*/
protected $rmaPushQueueManager;
/**
* RmaSyncCron constructor.
*
* @param RmaPushQueueManager $rmaPushQueueManager
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
RmaPushQueueManager $rmaPushQueueManager,
) {
parent::__construct($scheduleFactory, $scheduleCollectionFactory, $helper);
$this->rmaPushQueueManager = $rmaPushQueueManager;
}
/**
* get job code
* @return string
*/
public function getJobCode()
{
return $this->JOB_CODE;
}
/**
* get queue manager
* @return RmaPushQueueManager
*/
protected function getQueueManager()
{
return $this->rmaPushQueueManager;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace JR\NetSuite\Cron;
use JR\NetSuite\Queue\RmaPushQueueManager;
use Magento\Cron\Model\Schedule;
class RmaPushWorker extends AbstractSyncCron
{
/**
* @var string
*/
public $JOB_CODE = 'jr_netsuite_push_rma';
/**
* @var RmaPushQueueManager
*/
protected $rmaPushQueueManager;
/**
* RmaSyncCron constructor.
*
* @param RmaPushQueueManager $rmaPushQueueManager
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
RmaPushQueueManager $rmaPushQueueManager,
) {
parent::__construct($scheduleFactory, $scheduleCollectionFactory, $helper);
$this->rmaPushQueueManager = $rmaPushQueueManager;
}
/**
* get job code
* @return string
*/
public function getJobCode()
{
return $this->JOB_CODE;
}
/**
* get queue manager
* @return RmaPushQueueManager
*/
protected function getQueueManager()
{
return $this->rmaPushQueueManager;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace JR\NetSuite\Cron;
use JR\NetSuite\Queue\RmaQueueManager;
use Magento\Cron\Model\Schedule;
class RmaSyncCron extends AbstractSyncCron
{
/**
* @var string
*/
public $JOB_CODE = 'jr_netsuite_sync_rma';
/**
* @var RmaQueueManager
*/
protected $rmaQueueManager;
/**
* RmaSyncCron constructor.
*
* @param RmaQueueManager $rmaQueueManager
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
RmaQueueManager $rmaQueueManager,
) {
parent::__construct($scheduleFactory, $scheduleCollectionFactory, $helper);
$this->rmaQueueManager = $rmaQueueManager;
}
/**
* get job code
* @return string
*/
public function getJobCode()
{
return $this->JOB_CODE;
}
/**
* get queue manager
* @return RmaQueueManager
*/
protected function getQueueManager()
{
return $this->rmaQueueManager;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace JR\NetSuite\Cron;
use JR\NetSuite\Queue\RmaQueueManager;
use Magento\Cron\Model\Schedule;
class RmaSyncWorker extends AbstractSyncCron
{
/**
* @var string
*/
public $JOB_CODE = 'jr_netsuite_sync_rma';
/**
* @var RmaQueueManager
*/
protected $rmaQueueManager;
/**
* RmaSyncCron constructor.
*
* @param RmaQueueManager $rmaQueueManager
*/
public function __construct(
\Magento\Cron\Model\ScheduleFactory $scheduleFactory,
\Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $scheduleCollectionFactory,
\JR\NetSuite\Helper\Data $helper,
RmaQueueManager $rmaQueueManager,
) {
parent::__construct($scheduleFactory, $scheduleCollectionFactory, $helper);
$this->rmaQueueManager = $rmaQueueManager;
}
/**
* get job code
* @return string
*/
public function getJobCode()
{
return $this->JOB_CODE;
}
/**
* get queue manager
* @return RmaQueueManager
*/
protected function getQueueManager()
{
return $this->rmaQueueManager;
}
}
+340
View File
@@ -0,0 +1,340 @@
<?php
namespace JR\NetSuite\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Store\Model\ScopeInterface;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Customer\Model\CustomerFactory;
use JR\NetSuite\Model\NetSuiteFactory;
use JR\NetSuite\Model\MessageFactory;
use Magento\GiftMessage\Model\MessageFactory as GiftMessageFactory;
use Magento\Directory\Model\CountryFactory;
class Data extends AbstractHelper {
const XML_PATH_NETSUITE_ENABLE = 'jr_netsuite/general/enable';
const XML_PATH_MULTI_LOCATION_ENABLE = 'jr_netsuite/general/multi_location_enable';
const XML_PATH_OAUTH_ORDER_PUSH_ENABLE = 'jr_netsuite/cronScheduled/enable';
const XML_PATH_NETSUITE_COUNT_FROM = 'jr_netsuite/cronScheduled/netsuite_count_from';
const XML_PATH_NETSUITE_MAX_ATTEMPT = 'jr_netsuite/cronScheduled/netsuite_max_attempt';
const XML_PATH_NETSUITE_API_URL = 'jr_netsuite/apidetail/api_url';
const XML_PATH_NETSUITE_REALM = 'jr_netsuite/apidetail/oauth_realm';
const XML_PATH_NETSUITE_SCRIPT = 'jr_netsuite/apidetail/script';
const XML_PATH_NETSUITE_DEPLOY = 'jr_netsuite/apidetail/deploy';
const XML_PATH_NETSUITE_CONSUMER_KEY = 'jr_netsuite/apidetail/oauth_consumer_key';
const XML_PATH_NETSUITE_CONSUMER_SECRET = 'jr_netsuite/apidetail/oauth_consumer_secret';
const XML_PATH_DEFAULT_CUSTOMER_GROUP = 'jr_netsuite/default/customer_group';
const XML_PATH_DEFAULT_STORE_ID = 'jr_netsuite/default/store_id';
const XML_PATH_DEFAULT_TAX_CLASS = 'jr_netsuite/default/tax_class';
const XML_PATH_DEFAULT_CATEGORY = 'jr_netsuite/default/category';
const XML_PATH_DEFAULT_VISIBILITY_ID = 'jr_netsuite/default/visibility_id';
const XML_PATH_CRON_BATCH_SIZE = 'jr_netsuite/advanced/batch_size';
/**
* @var storeManager
*/
protected $storeManager;
/**
* @var scopeConfig
*/
protected $scopeConfig;
/**
* @var orderCollectionFactory
*/
protected $orderCollectionFactory;
/**
* @var \DateTime
*/
protected $_date;
/**
* @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
*/
protected $timezone;
/**
* @var customerFactory
*/
protected $customerFactory;
/**
* @var \JR\NetSuite\Logger\Logger
*/
protected $_logger;
/**
* @var netSuiteFactory
*/
protected $netSuiteFactory;
/**
* @var messageFactory
*/
protected $messageFactory;
/**
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory
* @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
* @param \Magento\Customer\Model\CustomerFactory $customerFactory
* @param \JR\NetSuite\Logger\Logger $logger
* @param \JR\NetSuite\Model\NetSuiteFactory $netSuiteFactory
* @param \Magento\GiftMessage\Model\MessageFactory $messageFactory
* @param \Magento\Directory\Model\CountryFactory $countryFactory
**/
public function __construct(
StoreManagerInterface $storeManager,
ScopeConfigInterface $scopeConfig,
CollectionFactory $orderCollectionFactory,
\Magento\Framework\Stdlib\DateTime\DateTime $date,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone,
CustomerFactory $customerFactory,
\JR\NetSuite\Logger\Logger $logger,
) {
$this->storeManager = $storeManager;
$this->scopeConfig = $scopeConfig;
$this->orderCollectionFactory = $orderCollectionFactory;
$this->_date = $date;
$this->timezone = $timezone;
$this->customerFactory = $customerFactory;
$this->_logger = $logger;
}
/**
* Get Logger
*
* @return \JR\NetSuite\Logger\Logger
*/
public function getLogger() {
return $this->_logger;
}
/**
* Get NetSuite API URL
*
* @return string
*/
public function getApiUrl() {
return $this->getConfigValue(self::XML_PATH_NETSUITE_API_URL);
}
/**
* Get NetSuite Enable
*
* @return string
*/
public function getNetSuiteIsEnabled() {
return $this->getConfigValue(self::XML_PATH_NETSUITE_ENABLE);
}
/**
* Get Multi Location Enable
*
* @return string
*/
public function getMultiLocationEnabled() {
return $this->getConfigValue(self::XML_PATH_MULTI_LOCATION_ENABLE);
}
/**
* Get Root Category
*
* @return string
*/
public function getDefaultCategory() {
return $this->getConfigValue(self::XML_PATH_DEFAULT_CATEGORY);
}
/**
* Get NetSuite visibility id
*
* @return string
*/
public function getDefaultVisibilityId() {
return $this->getConfigValue(self::XML_PATH_DEFAULT_VISIBILITY_ID);
}
/**
* Get NetSuite assign tax class
*
* @return string
*/
public function getDefaultTaxClass() {
return $this->getConfigValue(self::XML_PATH_DEFAULT_TAX_CLASS);
}
/**
* Get XML_PATH_NETSUITE_MAX_ATTEMPT
*
* @return string
*/
public function getNetSuiteMaxAttempt() {
return $this->getConfigValue(self::XML_PATH_NETSUITE_MAX_ATTEMPT);
}
/**
* Get XML_PATH_CRON_BATCH_SIZE
*
* @return string
*/
public function getCronBatchSize() {
return $this->getConfigValue(self::XML_PATH_CRON_BATCH_SIZE);
}
/**
* Get default_customer_group
*
* @return string
*/
public function getDefaultCustomerGroup() {
return $this->getConfigValue(self::XML_PATH_DEFAULT_CUSTOMER_GROUP);
}
/**
* Get default_store_id
*
* @return string
*/
public function getDefaultStoreId() {
return $this->getConfigValue(self::XML_PATH_DEFAULT_STORE_ID);
}
/**
* Get calculate date for order fatch
*
* @return \DateTime time
*/
public function getNetSuiteCountFromDate() {
$dayes = $this->getConfigValue(self::XML_PATH_NETSUITE_COUNT_FROM);
$currenctDate = $this->_date->date('Y-m-d H:i:s');
return $this->_date->date('Y-m-d H:i:s', (strtotime('-' . $dayes . ' day', strtotime($currenctDate))));
}
/**
* Get calculate date for order fatch
*
* @return \DateTime time
*/
public function getCurrentDate() {
return $this->_date->date('Y-m-d H:i:s');
}
public function convertUtcToLocalTime($utcDate, $format = 'Y-m-d H:i:s', $modify = null) {
$date = new \DateTime($utcDate, new \DateTimeZone('UTC'));
if (!empty($modify)) $date = $date->modify($modify);
$date->setTimezone(new \DateTimeZone($this->timezone->getConfigTimezone()));
return $date->format($format);
}
public function convertLocalTimeToUtc($localTimeString, $format = "Y-m-d H:i:s") {
try {
// Assum ing $localTimeString is in a specific format, e.g., "Y-m-d H:i:s"
$date = new \DateTime($localTimeString, new \DateTimeZone($this->timezone->getConfigTimezone()));
if (!$date) {
throw new \Exception("Invalid date format");
}
// Convert to UTC
$date->setTimezone(new \DateTimeZone('UTC'));
return $date->format($format); // Format as needed for the database
} catch (\Exception $e) {
// Handle the exception as needed
return null;
}
}
/**
* Get NetSuite Config value
*
* @return string
*/
public function getConfigValue($path) {
$store = $this->getStoreId();
$config_data = $this->scopeConfig->getValue($path, ScopeInterface::SCOPE_STORE, $store);
return $config_data;
}
/**
* Get store id
* @return int
*/
public function getStoreId() {
return $this->storeManager->getStore()->getStoreId();
}
public function convertStringToCode($string) {
return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');
}
public function formatBytes($bytes) {
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
$bytes = number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
$bytes = $bytes . ' bytes';
} elseif ($bytes == 1) {
$bytes = $bytes . ' byte';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
public function nDigitRandom($digits) {
return rand(pow(10, $digits - 1) - 1, pow(10, $digits) - 1);
}
public function secondsToTime($s) {
$h = floor($s / 3600);
$s -= $h * 3600;
$m = floor($s / 60);
$s -= $m * 60;
return $h . ':' . sprintf('%02d', $m) . ':' . sprintf('%02d', $s);
}
//This function transforms the php.ini notation for numbers (like '2M') to an integer (2*1024*1024 in this case)
public function convertPHPSizeToBytes($sSize) {
if (is_numeric($sSize)) {
return $sSize;
}
$sSuffix = substr($sSize, -1);
$iValue = substr($sSize, 0, -1);
switch (strtoupper($sSuffix)) {
case 'P':
$iValue *= 1024;
break;
case 'T':
$iValue *= 1024;
break;
case 'G':
$iValue *= 1024;
break;
case 'M':
$iValue *= 1024;
break;
case 'K':
$iValue *= 1024;
break;
}
return $iValue;
}
}
+269
View File
@@ -0,0 +1,269 @@
<?php
namespace JR\NetSuite\Lib;
use JR\NetSuite\Helper\Data;
use JR\NetSuite\Logger\Logger;
use JR\NetSuite\Lib\Oauth;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\Serialize\Serializer\Json;
class NetSuiteAPI
{
const CUSTOMER = 'customer';
const CUSTOMER_WITH_FILTER = 'customerWithFilter';
const RETURN_AUTHORIZATION = 'returnAuthorization';
const INVENTORY_ITEM = 'inventoryItem';
const INVENTORY_ITEM_WITH_LOCATION = 'inventoryItemWithLocation';
const LOCATION = 'location';
const SALES_ORDER = 'salesOrder';
const CREATE_LEAD_SCRIPT = '351';
const CREATE_SALES_ORDER_SCRIPT = '468';
const DEFAULT_PAGE_SIZE = 150;
const DEFAULT_PAGE = 1;
/**
* @var \JR\NetSuite\Helper\Data
*/
protected $helper;
/**
* @var \JR\NetSuite\Logger\Logger
*/
protected $_logger;
/**
* @var \JR\NetSuite\Lib\Oauth
*/
protected $oauth;
/**
* @var \Magento\Framework\HTTP\Client\Curl
*/
public $curl;
/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
public $json;
/**
* @param Data $helper
* @param Logger $_logger
*/
public function __construct(
Data $helper,
Logger $logger,
Oauth $oauth,
Curl $curl,
Json $json
) {
$this->helper = $helper;
$this->_logger = $logger;
$this->oauth = $oauth;
$this->curl = $curl;
$this->json = $json;
}
/**
* fetch customer data from NetSuite
*
* @param $pageSize
* @param $page
* @param $addtionalParams
* @return array
*/
public function fetchCustomers($pageSize = self::DEFAULT_PAGE_SIZE, $page = 1, $addtionalParams = [])
{
return $this->fetchData(self::CUSTOMER, $pageSize, $page, $addtionalParams);
}
/**
* fetch customer data from NetSuite by email
*
* @param $pageSize
* @param $page
* @param $addtionalParams
* @return array
*/
public function fetchCustomersWithFilter($pageSize = self::DEFAULT_PAGE_SIZE, $page = 1, $addtionalParams = [])
{
// TODO: filter not right for new lead
return $this->fetchData(self::CUSTOMER_WITH_FILTER, $pageSize, $page, $addtionalParams);
}
/**
* fetch return authorization data from NetSuite
*
* @param $pageSize
* @param $page
* @return array
*/
public function fetchReturnAuthorizations($pageSize = self::DEFAULT_PAGE_SIZE, $page = self::DEFAULT_PAGE, $addtionalParams = [])
{
return $this->fetchData(self::RETURN_AUTHORIZATION, $pageSize, $page, $addtionalParams);
}
/**
* fetch location data from NetSuite
*
* @param $pageSize
* @param $page
* @return array
*/
public function fetchLocations($pageSize = self::DEFAULT_PAGE_SIZE, $page = self::DEFAULT_PAGE, $addtionalParams = [])
{
return $this->fetchData(self::LOCATION, $pageSize, $page, $addtionalParams);
}
/**
* fetch product data from NetSuite
*
* @param $pageSize
* @param $page
* @return array
*/
public function fetchProducts($pageSize = self::DEFAULT_PAGE_SIZE, $page = self::DEFAULT_PAGE, $addtionalParams = [])
{
return $this->fetchData(self::INVENTORY_ITEM, $pageSize, $page, $addtionalParams);
}
/**
* fetch product data from NetSuite
*
* @param $pageSize
* @param $page
* @return array
*/
public function fetchProductsWithLocation($pageSize = self::DEFAULT_PAGE_SIZE, $page = self::DEFAULT_PAGE, $addtionalParams = [])
{
return $this->fetchData(self::INVENTORY_ITEM_WITH_LOCATION, $pageSize, $page, $addtionalParams);
}
/**
* fetch sales order data from NetSuite
*
* @param $pageSize
* @param $page
* @return array
*/
public function fetchOrders($pageSize = self::DEFAULT_PAGE_SIZE, $page = self::DEFAULT_PAGE, $addtionalParams = [])
{
return $this->fetchData(self::SALES_ORDER, $pageSize, $page, $addtionalParams);
}
/**
* fetch data from NetSuite
*
* @param $recordType
* @param $pageSize
* @param $page
* @return array
*/
private function fetchData($recordType, $pageSize = self::DEFAULT_PAGE_SIZE, $page = self::DEFAULT_PAGE, $addtionalParams = [])
{
$params = [
'recordType' => $recordType,
'page' => $page,
'pageSize' => $pageSize
];
if (!empty($addtionalParams)) {
$params = array_merge($params, $addtionalParams);
}
$response = $this->postData($params);
return $response;
}
/**
* update customer data to NetSuite
*/
public function updateCustomer($data)
{
$this->oauth->setScript(self::CREATE_LEAD_SCRIPT);
$response = $this->postData($data);
return $response;
}
/**
* update order data to NetSuite
*/
public function updateOrder($data)
{
$this->oauth->setScript(self::CREATE_SALES_ORDER_SCRIPT);
$response = $this->postData($data);
return $response;
}
/**
* create return authorization in NetSuite
*/
public function createReturnAuthorization($data)
{
$params = [
'action' => 'create',
'recordType' => self::RETURN_AUTHORIZATION,
'data' => $data
];
$response = $this->postData($params);
return $response;
}
/**
* update data to NetSuite
*/
public function updateData($recordType, $data)
{
$params = [
'recordType' => $recordType,
'data' => $data
];
$response = $this->postData($params);
return $response;
}
/**
* @param array $data
* @return array
*/
public function postData(array $data)
{
$url = $this->oauth->getApiUrl() . '?script=' . $this->oauth->getScript() . '&deploy=1';
$oauthCredentials = $this->oauth->getOauthParams('POST');
$jsonData = $this->json->serialize($data);
$this->_logger->info('Request: ' . $jsonData);
try {
$this->curl->addHeader("Accept", "application/json");
$this->curl->addHeader("Content-Type", "application/json");
$this->curl->addHeader("Authorization", $oauthCredentials);
// $this->curl->addHeader("Cookie", "NS_ROUTING_VERSION=LAGGING");
$this->curl->post($url, $jsonData);
// check the status code returned by NetSuite
$statusCode = $this->curl->getStatus();
$this->_logger->info('Status Code: ' . $statusCode);
$this->_logger->info('NetSuite API data: ', ['data' => $data, 'url' => $url]);
if ($statusCode != 200) {
$this->_logger->error("Error: " . $this->curl->getBody());
return $response = [
'error' => true,
'message' => $this->curl->getBody()
];
}
$response = $this->curl->getBody();
$this->_logger->info('Response: ' . $response);
$response = $this->json->unserialize($response);
# if response is not an array, unserialize again
if (!is_array($response)) {
$response = $this->json->unserialize($response);
}
return $response;
} catch (\Exception $e) {
$this->_logger->error("error: " . $e->getMessage());
return $response = [
'error' => true,
'message' => $e->getMessage()
];
}
}
}
+215
View File
@@ -0,0 +1,215 @@
<?php
namespace JR\NetSuite\Lib;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
class Oauth
{
const SIGNATURE_METHOD_HMACSHA256 = 'HMAC-SHA256';
const OAUTH_SCRIPT = 'jr_netsuite/apidetail/script';
const OAUTH_VERSION = '1.0';
const NONCE_STRING = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const XML_PATH_OAUTH_URL = 'jr_netsuite/apidetail/api_url';
const XML_PATH_OAUTH_REALM = 'jr_netsuite/apidetail/oauth_realm';
const XML_PATH_OAUTH_CONSUMER_KEY = 'jr_netsuite/apidetail/oauth_consumer_key';
const XML_PATH_OAUTH_CONSUMER_SECRET = 'jr_netsuite/apidetail/oauth_consumer_secret';
const XML_PATH_OAUTH_TOKEN = 'jr_netsuite/apidetail/oauth_token';
const XML_PATH_OAUTH_TOKEN_SECRET = 'jr_netsuite/apidetail/oauth_token_secret';
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var string
*/
protected $script;
/**
* @param StoreManagerInterface $storeManager
* @param ScopeConfigInterface $scopeConfig
**/
public function __construct(
StoreManagerInterface $storeManager,
ScopeConfigInterface $scopeConfig
) {
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
}
/**
* consumer key
* @return string
*/
public function getConsumerKey()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_CONSUMER_KEY);
}
/**
* consumer Secret
* @return string
*/
public function getConsumerSecret()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_CONSUMER_SECRET);
}
/**
* Token access key
* @return string
*/
public function getToken()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_TOKEN);
}
/**
* Token Secret
* @return string
*/
public function getTokenSecret()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_TOKEN_SECRET);
}
/**
* Token Secreat
* @return string
*/
public function getRealm()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_REALM);
}
/**
* Set Token Script
* @return string
*/
public function setScript($script)
{
$this->script = $script;
}
/**
* Token script
* @return string
*/
public function getScript()
{
if ($this->script) {
return $this->script;
}
return $this->getConfigValue(self::OAUTH_SCRIPT);
}
/**
* Token Secreat
* @return string
*/
public function getApiUrl()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_URL);
}
/**
* Calculate header for request
* @return string
*/
public function getOauthParams($method = 'POST')
{
$time = time();
$nonce = rawurlencode($this->generateNonceString(11));
$oauthparams = $this->getParamObject($nonce, $time);
$baseString = $this->createBaseString($method, $oauthparams);
$signature = $this->getSignature('sha256', $baseString);
return $this->buildAuthorizationHeader($nonce, $time, $signature);
}
/**
* Calculate signature for request
* @return string
*/
public function getSignature($algo, $baseString)
{
$key = rawurlencode($this->getConsumerSecret()) . '&' . rawurlencode($this->getTokenSecret());
return rawurlencode(base64_encode(hash_hmac($algo, $baseString, $key, true)));
}
/**
* Builds the Authorization header for a request
* @return string
*/
private function buildAuthorizationHeader($nonce, $time, $signature)
{
return 'OAuth realm="' . $this->getRealm() . '",oauth_consumer_key="' . $this->getConsumerKey() . '",oauth_token="' . $this->getToken() . '",oauth_signature_method="HMAC-SHA256",oauth_timestamp="' . $time . '",oauth_nonce="' . $nonce . '",oauth_version="1.0",oauth_signature="' . $signature . '"';
}
/**
* Creates the Signature Base String.
* The Signature Base String is a consistent reproducible concatenation of
* the request elements into a single string. The string is used as an
* input in hashing or signing algorithms.
* @return string Returns the base string
*/
private function createBaseString($method, $params)
{
$url = $this->getApiUrl();
$query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
return strtoupper($method)
. '&' . rawurlencode($url)
. '&' . rawurlencode($query);
}
/**
* generating nonce value
* @return string
*/
public function generateNonceString($length = 11)
{
$characters = self::NONCE_STRING;
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
/**
* generating param value
* @return array
*/
public function getParamObject($nonce, $time)
{
return [
'deploy' => 1,
"oauth_consumer_key" => $this->getConsumerKey(),
"oauth_nonce" => $nonce,
"oauth_signature_method" => self::SIGNATURE_METHOD_HMACSHA256,
"oauth_timestamp" => $time,
"oauth_token" => $this->getToken(),
"oauth_version" => self::OAUTH_VERSION,
'script' => $this->getScript()
];
}
/**
* get config value
* @return string
*/
public function getConfigValue($path)
{
$store = $this->storeManager->getStore()->getStoreId();
$config_data = $this->scopeConfig->getValue($path, ScopeInterface::SCOPE_STORE, $store);
return $config_data;
}
}
+200
View File
@@ -0,0 +1,200 @@
<?php
namespace JR\NetSuite\Lib\Restful;
use JR\NetSuite\Cron\OrderSyncWorker;
use JR\NetSuite\Helper\Data;
use JR\NetSuite\Logger\Logger;
use Lts\Sales\Cron\OrderNetsuiteSync;
use Magento\Framework\Exception\InvalidArgumentException;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\Serialize\Serializer\Json;
use GuzzleHttp\Client;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
use GuzzleHttp\HandlerStack;
class NetSuiteAPI
{
const CUSTOMER = 'customer';
const LOCATION = 'location';
/**
* @var \JR\NetSuite\Helper\Data
*/
protected $helper;
/**
* @var \JR\NetSuite\Logger\Logger
*/
protected $_logger;
/**
* @var \JR\NetSuite\Lib\Restful\Oauth
*/
protected \JR\NetSuite\Lib\Restful\Oauth $oauth;
/**
* @var \Magento\Framework\HTTP\Client\Curl
*/
public $curl;
/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
public $json;
public array $responseHeaders;
/**
* @param Data $helper
* @param Logger $_logger
*/
public function __construct(
Data $helper,
Logger $logger,
Oauth $oauth,
Curl $curl,
Json $json
) {
$this->helper = $helper;
$this->_logger = $logger;
$this->oauth = $oauth;
$this->curl = $curl;
$this->json = $json;
}
/**
* @param array $data
* @return array
* @throws InvalidArgumentException
*/
public function postData(string $service, array $data)
{
$url = $this->oauth->getEndpoint($service);
$this->responseHeaders = [];
$oauthCredentials = $this->oauth->getOauthParams($service);
$jsonData = $this->json->serialize($data);
// $this->_logger->info('Restful Request data: ' . $jsonData);
// $this->_logger->info('Restful Request oauthCredentials: ' . $oauthCredentials);
try {
$this->curl->addHeader("Accept", "application/json");
$this->curl->addHeader("Content-Type", "application/json");
$this->curl->addHeader("Authorization", $oauthCredentials);
// $this->curl->addHeader("Cookie", "NS_ROUTING_VERSION=LAGGING");
$this->curl->post($url, $jsonData);
// check the status code returned by NetSuite
$statusCode = $this->curl->getStatus();
// $this->_logger->info('Restful Status Code: ' . $statusCode);
// $this->_logger->info('Restful NetSuite API data: ', ['data' => $data, 'url' => $url]);
$header = $this->curl->getHeaders();
$this->responseHeaders = $header;
if (!str_starts_with($statusCode, '2')) {
// $this->_logger->error("Error: " . $this->curl->getBody());
return [
'error' => true,
'message' => $this->curl->getBody()
];
}
if ($statusCode==204) {
return [
'error' => false,
];
}
$response = $this->curl->getBody();
$response = $this->json->unserialize($response);
# if response is not an array, unserialize again
if (!is_array($response)) {
$response = $this->json->unserialize($response);
}
return $response;
} catch (\Exception $e) {
$this->_logger->error("Restful error: " . $e->getMessage(), $e->getTrace());
return $response = [
'error' => true,
'message' => $e->getMessage()
];
}
}
/**
* @return array
*/
public function getResponseHeaders()
{
return $this->responseHeaders;
}
/**
* @param string $service
* @param array $params
* @return array
* @throws \Random\RandomException
*/
public function get(string $service, array $params = [])
{
$consumerKey = $this->oauth->getConsumerKey();
$consumerSecret = $this->oauth->getConsumerSecret();
$token = $this->oauth->getToken();
$token_secret = $this->oauth->getTokenSecret();
$realm = $this->oauth->getAccountId();
// OAuth parameters
$oauth = [
'oauth_consumer_key' => $consumerKey,
'oauth_token' => $token,
'oauth_nonce' => bin2hex(random_bytes(16)),
'oauth_timestamp' => time(),
'oauth_signature_method' => Oauth::SIGNATURE_METHOD_HMACSHA256,
'oauth_version' => '1.0'
];
$url = $this->oauth->getEndpoint($service);
// Combine and sort parameters for signature
$all_params = array_merge($params, $oauth);
ksort($all_params);
// Build base string
$base_info = 'GET&' . rawurlencode($url) . '&' . rawurlencode(http_build_query($all_params, '', '&', PHP_QUERY_RFC3986));
// Create signature key
$composite_key = rawurlencode($consumerSecret) . '&' . rawurlencode($token_secret);
// Generate the signature
$oauth_signature = base64_encode(hash_hmac('sha256', $base_info, $composite_key, true));
// Add the signature to the OAuth parameters
$oauth['oauth_signature'] = $oauth_signature;
// Build the Authorization header
$header = 'OAuth realm="' . rawurlencode($realm) . '"';
foreach ($oauth as $key => $value) {
$header .= ', ' . rawurlencode($key) . '="' . rawurlencode($value) . '"';
}
$fullUrl = $url . '?' . http_build_query($params, '', null, PHP_QUERY_RFC3986);
// Send the GET request with cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fullUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: $header"]);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status != 200) {
$this->_logger->error("netsuite get request fail: ", ['url' => $fullUrl, 'response' => $response, 'http_code' => $status]);
}
return [
'error' => $status != 200,
'response' => json_decode($response, true)
];
}
}
+220
View File
@@ -0,0 +1,220 @@
<?php
namespace JR\NetSuite\Lib\Restful;
use JR\NetSuite\Logger\Logger;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\InvalidArgumentException;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
class Oauth
{
const SIGNATURE_METHOD_HMACSHA256 = 'HMAC-SHA256';
const OAUTH_VERSION = '1.0';
const NONCE_STRING = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const XML_PATH_RESTFUL_ENDPOINT = 'jr_netsuite/restful/service_endpoint';
const XML_PATH_ACCOUNT_ID = 'jr_netsuite/restful/account_id';
const XML_PATH_OAUTH_CONSUMER_KEY = 'jr_netsuite/apidetail/oauth_consumer_key';
const XML_PATH_OAUTH_CONSUMER_SECRET = 'jr_netsuite/apidetail/oauth_consumer_secret';
const XML_PATH_OAUTH_TOKEN = 'jr_netsuite/apidetail/oauth_token';
const XML_PATH_OAUTH_TOKEN_SECRET = 'jr_netsuite/apidetail/oauth_token_secret';
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var string
*/
protected $script;
private Logger $logger;
/**
* @param StoreManagerInterface $storeManager
* @param ScopeConfigInterface $scopeConfig
**/
public function __construct(
StoreManagerInterface $storeManager,
ScopeConfigInterface $scopeConfig,
Logger $logger
) {
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
$this->logger = $logger;
}
/**
* consumer key
* @return string
*/
public function getConsumerKey()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_CONSUMER_KEY);
}
/**
* consumer Secret
* @return string
*/
public function getConsumerSecret()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_CONSUMER_SECRET);
}
/**
* Token access key
* @return string
*/
public function getToken()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_TOKEN);
}
/**
* Token Secret
* @return string
*/
public function getTokenSecret()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_TOKEN_SECRET);
}
/**
* @return string
*/
public function getAccountId(): string
{
return $this->getConfigValue(self::XML_PATH_ACCOUNT_ID);
}
/**
* @param string $service
* @return string
*/
public function getEndpoint(string $service = ''): string
{
$endpoint = $this->getConfigValue(self::XML_PATH_RESTFUL_ENDPOINT);
if ($service) {
$endpoint = $endpoint .'/'.ltrim($service, '/');
}
return $endpoint;
}
/**
* @param string $service, for example, if you want to sync customer to netsuite, this param is record/v1/customer
* @param string $method
* @return string
* @throws InvalidArgumentException
*/
public function getOauthParams(string $service, string $method = 'POST')
{
if (!$service) {
throw new InvalidArgumentException(__('Parameter service name is required.'));
}
$time = time();
$nonce = rawurlencode($this->generateNonceString(11));
$oauthparams = $this->getParamObject($nonce, $time);
$baseString = $this->createBaseString($service, $method, $oauthparams );
$signature = $this->getSignature('sha256', $baseString);
return $this->buildAuthorizationHeader($nonce, $time, $signature);
}
/**
* Calculate signature for request
* @return string
*/
public function getSignature($algo, $baseString)
{
$key = rawurlencode($this->getConsumerSecret()) . '&' . rawurlencode($this->getTokenSecret());
return rawurlencode(base64_encode(hash_hmac($algo, $baseString, $key, true)));
}
/**
* Builds the Authorization header for a request
* @return string
*/
private function buildAuthorizationHeader($nonce, $time, $signature)
{
return 'OAuth realm="' . $this->getAccountId() . '",oauth_consumer_key="' . $this->getConsumerKey() .
'",oauth_token="' . $this->getToken() . '",oauth_signature_method="'.self::SIGNATURE_METHOD_HMACSHA256.
'",oauth_timestamp="' . $time . '",oauth_nonce="' . $nonce . '",oauth_version="1.0",oauth_signature="'
. $signature . '"';
}
/**
* Creates the Signature Base String.
* The Signature Base String is a consistent reproducible concatenation of
* the request elements into a single string. The string is used as an
* input in hashing or signing algorithms.
* @param string $service
* @param string $method
* @param array $params
* @return string
*/
private function createBaseString(string $service, string $method, array $params = [])
{
$url = $this->getEndpoint().'/'.$service;
$rawString = strtoupper($method). '&' . rawurlencode($url);
if ($params) {
$rawString .= '&';
ksort($params);
$rawString .= rawurlencode(http_build_query($params, '', '&', PHP_QUERY_RFC3986));
}
return $rawString;
}
/**
* generating nonce value
* @return string
*/
public function generateNonceString($length = 11)
{
$characters = self::NONCE_STRING;
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
/**
* generate param value
* @param $nonce
* @param $time
* @return array
*/
public function getParamObject(string $nonce, string $time)
{
return [
"oauth_consumer_key" => $this->getConsumerKey(),
"oauth_nonce" => $nonce,
"oauth_signature_method" => self::SIGNATURE_METHOD_HMACSHA256,
"oauth_timestamp" => $time,
"oauth_token" => $this->getToken(),
"oauth_version" => self::OAUTH_VERSION,
];
}
/**
* get config value
* @return string
*/
public function getConfigValue($path)
{
$store = $this->storeManager->getStore()->getStoreId();
return $this->scopeConfig->getValue($path, ScopeInterface::SCOPE_STORE, $store);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace JR\NetSuite\Logger;
use Magento\Framework\Filesystem\DriverInterface;
use Monolog\Formatter\LineFormatter;
class Handler extends \Magento\Framework\Logger\Handler\Base
{
// protected $fileName = '/var/log/jr_netsuite_sync.log';
protected $loggerType = \Monolog\Logger::DEBUG;
public function __construct(
DriverInterface $filesystem,
?string $filePath = null,
?string $fileName = null
) {
$this->fileName = '/var/log/jr_netsuite_sync/'.date('Ymd').'.log';
parent::__construct($filesystem, $filePath, $fileName);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace JR\NetSuite\Logger;
class Logger extends \Monolog\Logger
{
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace JR\NetSuite\Mapper;
use JR\NetSuite\Model\Data\ProductQueueItem;
// the common mapping logic that can be used for any entity type
abstract class AbstractMapper
{
/**
* @var ProductQueueItem
*/
protected $queueItem;
/**
* @param ProductQueueItem $queueItem
*/
public function __construct(
ProductQueueItem $queueItem
) {
$this->queueItem = $queueItem;
}
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
abstract public function convertToMagentoFormat($netSuiteData);
/**
* Convert data from Magento format to NetSuite format.
*
* @param array $magentoData
* @return array
*/
abstract public function convertToNetSuiteFormat($magentoData);
}
+490
View File
@@ -0,0 +1,490 @@
<?php
namespace JR\NetSuite\Mapper;
use JR\NetSuite\Mapper\AbstractMapper;
use Magento\Directory\Model\RegionFactory;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Api\Data\AddressInterfaceFactory;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Framework\Event\ManagerInterface as EventManager;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Directory\Model\CountryFactory;
// Handles the specifics of mapping product data.
class CustomerMapper {
const STATUSES = [
'13' => 'Customer-Active',
'21' => 'Customer-Bad Debt',
'20' => 'Customer-Blacklist',
'22' => 'Customer-Fraudulent',
'15' => 'Customer-Inactive',
'23' => 'Customer-New',
'17' => 'Lead-Free',
'6' => 'Lead-New',
'18' => 'Lead-Pending Approval',
'7' => 'Lead-Unqualified',
'8' => 'Prospect-In Discussion',
'10' => 'Prospect-Proposal',
];
/**
* customer group
*
* @var string
*/
protected $default_customer_group;
/**
* helper
*
* @var \JR\NetSuite\Helper\Data
*/
protected $helper;
/**
* array to store customer group id.
*
* @var int
*/
protected $customerGroupIdMap = [];
/**
* @var RegionFactory
*/
protected $regionFactory;
/**
* @var \Magento\Customer\Model\GroupFactory
*/
protected $customerGroupFactory;
/**
* @var GroupRepositoryInterface
*/
protected $groupRepository;
/**
* @var SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;
/**
* @var CustomerRepositoryInterface
*/
protected $customerRepository;
/**
* @var CustomerInterfaceFactory
*/
protected $customerFactory;
/**
* @var AddressInterfaceFactory
*/
protected $addressFactory;
/**
* @var EventManager
*/
protected $eventManager;
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var CountryFactory
*/
protected $countryFactory;
/**
* CustomerMapper constructor.
*/
public function __construct(
RegionFactory $regionFactory,
\Magento\Customer\Model\GroupFactory $customerGroupFactory,
GroupRepositoryInterface $groupRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
\JR\NetSuite\Helper\Data $helper,
CustomerRepositoryInterface $customerRepository,
CustomerInterfaceFactory $customerFactory,
AddressInterfaceFactory $addressFactory,
EventManager $eventManager,
StoreManagerInterface $storeManager,
CountryFactory $countryFactory
) {
$this->regionFactory = $regionFactory;
$this->customerGroupFactory = $customerGroupFactory;
$this->groupRepository = $groupRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->helper = $helper;
$this->default_customer_group = $this->helper->getDefaultCustomerGroup();
$this->customerRepository = $customerRepository;
$this->customerFactory = $customerFactory;
$this->addressFactory = $addressFactory;
$this->eventManager = $eventManager;
$this->storeManager = $storeManager;
$this->countryFactory = $countryFactory;
}
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
public function convertToMagentoFormat($netSuiteData) {
/*
[internalid] => 246911
[isinactive] =>
[entityid] => 08/03NJ-MET-NC
[entitystatus] => 8
[addressee] => Modern Edge Technologies
[addressphone] => (336) 699-2158
[email] => babbott@modernedgetechnology.com
[phone] => (336) 699-2158
[balance] => .00
[creditlimit] => 1.00
[billattention] => Black Abbott
[billaddress1] => 6629 Old U.S. 421
[billaddress2] =>
[billaddressee] => Modern Edge Technologies
[billcity] => East Bend
[billcountry] => US
[billstate] => NC
[billzipcode] => 27018
[isdefaultbilling] => 1
[isperson] =>
[firstname] =>
[lastname] =>
[companyname] => Modern Edge Technologies
[shipaddress1] => 6629 Old U.S. 421
[shipaddress2] =>
[shipaddressee] => Modern Edge Technologies
[shipattention] => Black Abbott
[shipcity] => East Bend
[shipcomplete] =>
[shipcountry] => US
[shippingcarrier] =>
[shipstate] => NC
[shipzip] => 27018
[isdefaultshipping] => 1
*/
// echo json_encode($netSuiteData, JSON_PRETTY_PRINT) . "\n";
// convert netsuite data to magento data
$magentoData = [];
foreach ($netSuiteData as $data) {
$name = $this->filterFirstNonEmpty([
$data['shipattention'] ?? '',
$data['billattention'] ?? '',
$data['addressee'] ?? '',
$data['companyname'],
]);
$convertedData = [
'is_active' => $data['isinactive'] ? 0 : 1,
'netsuite_entity_id' => $data['entityid'],
'netsuite_customer_id' => $data['internalid'],
'status' => self::STATUSES[$data['entitystatus']],
'firstname' => count($name) > 0 ? array_shift($name) : $this->replaceName($data['companyname']),
'lastname' => count($name) > 0 ? (empty(implode(' ', $name)) ? $this->replaceName($data['companyname']) : implode(' ', $name)) : $this->replaceName($data['companyname']),
'email' => $data['email'],
'company_name' => $data['companyname'],
'phone' => $data['phone'],
'group_id' => $this->getDefaultCustomerGroupId(),
'reporting_office' => $data['cseg_ncg_rep_office'],
'isdefaultshipping' => $data['isdefaultshipping'],
'isdefaultbilling' => $data['isdefaultbilling'],
];
$shipaddressee = $this->filterFirstNonEmpty([
$data['shipattention'],
$data['shipaddressee'],
$data['billattention'] ?? '',
]);
if (empty($shipaddressee)) {
$shipaddressee = $this->getNameFromAddressText($data['shipaddress']);
}
$convertedData['shipping_address'] = [
'firstname' => count($shipaddressee) > 0 ? array_shift($shipaddressee) : '',
'lastname' => count($shipaddressee) > 0 ? implode(' ', $shipaddressee) : $data['companyname'],
'company' => $data['companyname'],
'street' => $data['shipaddress1'] != '' ?
[$data['shipaddress1'], $data['shipaddress2']] :
[$data['billaddress1'], $data['billaddress2']],
'city' => $data['shipcity'],
'country_id' => $data['shipcountry'],
// 'region' => $data['shipstate'],
'region_id' => $this->getRegion($data['shipcountry'], $data['shipstate'])->getId(),
'postcode' => $data['shipzip'],
'telephone' => $data['addressphone'] == '' ? $data['phone'] : $data['addressphone'],
];
$billaddressee = $this->filterFirstNonEmpty([
$data['billattention'],
$data['billaddressee'],
$data['shipattention'] ?? '',
]);
if (empty($billaddressee)) {
$billaddressee = $this->getNameFromAddressText($data['billaddress']);
}
$convertedData['billing_address'] = [
'firstname' => count($billaddressee) > 0 ? array_shift($billaddressee) : '',
'lastname' => count($billaddressee) > 0 ?
(empty(implode(' ', $billaddressee)) ? $data['companyname'] : implode(' ', $billaddressee)) : $data['companyname'],
'company' => $data['companyname'],
'street' => [$data['billaddress1'], $data['billaddress2']],
'city' => $data['billcity'],
'country_id' => $data['billcountry'],
// 'region' => $data['billstate'],
'region_id' => $this->getRegion($data['billcountry'], $data['billstate'])->getId(),
'postcode' => $data['billzipcode'],
'telephone' => $data['addressphone'] == '' ? $data['phone'] : $data['addressphone'],
];
// 'phone' => $data['phone'],
// 'fax' => $data['fax'],
// 'website' => $data['url'],
// 'street' => $data['address1'],
// 'city' => $data['city'],
// 'country_id' => $data['country'],
// 'region' => $data['state'],
// 'postcode' => $data['zip'],
// 'created_at' => $data['createddate'],
// 'updated_at' => $data['lastmodifieddate']
$magentoData[] = $convertedData;
}
return $magentoData;
}
/**
* Convert data from Magento format to NetSuite format.
*
* @param array $magentoData
* @return array
*/
public function convertToNetSuiteFormat($magentoData) {
// Your conversion logic here
}
/**
* convert magento customer to netsuite format by email
*/
public function convertToNetSuiteFormatByEmail($email) {
$customer = $this->customerRepository->get($email);
$phone = $customer->getCustomAttribute('phone')?->getValue();
$company = $customer->getCustomAttribute('company')?->getValue();
$defaultBillingAddressId = $customer->getDefaultBilling() ?? null;
$defaultShippingAddressId = $customer->getDefaultShipping() ?? null;
$netsuiteAddressList = [];
$addresses = $customer->getAddresses();
foreach ($addresses as $address) {
$netsuiteAddress = new \stdClass(); // Assuming stdClass for simplicity, replace with actual class if applicable
$netsuiteAddress->attention = $customer->getFirstname() . ' ' . $customer->getLastname();
$street = array_filter($address->getStreet());
if (count($street) == 1) {
$street = explode(",", $street[0]);
if (count($street) > 2) {
$street1 = trim(implode(",", array_slice($street, 0, count($street) - 1)));
} else {
$street1 = trim($street[0]);
}
if (count($street) > 1) {
$street2 = trim($street[count($street) - 1]);
}
}
$netsuiteAddress->addr1 = $street1 ?? '';
$netsuiteAddress->addr2 = $street2 ?? '';
$netsuiteAddress->city = $address->getCity() ?? '';
$netsuiteAddress->zip = $address->getPostcode() ?? '';
$netsuiteAddress->state = $address->getRegion()?->getRegionCode() ?? '';
$netsuiteAddress->country = $address->getCountryId() ?? '';
$phone = $phone ?? $address->getTelephone();
$company = $company ?? $address->getCompany();
// Dispatch event or additional processing
// $this->eventManager->dispatch('netsuite_address_create_before', ['netsuite_address' => $netsuiteAddress]);
$netsuiteAddressList[] = [
'defaultbilling' => $address->getId() == $defaultBillingAddressId,
'defaultshipping' => $address->getId() == $defaultShippingAddressId,
'address' => $netsuiteAddress,
];
}
if (!empty($phone)) {
$phone = preg_replace('/[^0-9]/', '', $phone);
if (strlen($phone) == 10) {
$phone = '0001' . $phone;
}
$phone = str_pad($phone, 14, '0', STR_PAD_LEFT);
}
$netsuiteCustomer = [
//"requestTime": 40780772495802300,
'requestTime' => time(),
'firstName' => $customer->getFirstname(),
'lastName' => $customer->getLastname(),
'addressBooks' => $netsuiteAddressList,
'isPerson' => "T",
'phone' => $phone ?? '',
'companyname' => $company ?? '',
'custentity_source' => 3,
'entityid' => 'magento_' . $customer->getId(),
'leadsource' => -6,
'title' => $customer->getPrefix() ?? '',
'email' => $customer->getEmail(),
];
return $netsuiteCustomer;
}
/**
* Convert data to NetSuite format by order
*
* @param OrderInterface $order
* @return array
*/
public function convertToNetSuiteFormatByOrder(OrderInterface $order) {
if ($customerData = $this->convertToNetSuiteFormatByEmail($order->getCustomerEmail())) {
return $customerData;
}
$customer = $this->customerFactory->create();
$customer->setEmail($order->getCustomerEmail())
->setFirstname($order->getCustomerFirstname())
->setLastname($order->getCustomerLastname() ?: $order->getCustomerFirstname())
->setMiddlename($order->getCustomerMiddlename())
->setStoreId($order->getStoreId());
// Assuming setPrimaryBillingAddress() and setPrimaryShippingAddress() logic is handled separately,
// as Magento 2 uses addresses linked to customer entities differently than Magento 1
// Add customer addresses
$billingAddress = $this->addressFactory->create()->setData($order->getBillingAddress()->getData());
$shippingAddress = $this->addressFactory->create()->setData($order->getShippingAddress()->getData());
$customer->setAddresses([$billingAddress, $shippingAddress]);
// Convert to Netsuite format and send to Netsuite
// Assuming getNetsuiteFormat is an available method that transforms Magento customer to Netsuite format
$netsuiteCustomer = $this->getNetsuiteFormat($customer);
if ($netsuiteCustomer->externalId == 0) {
$netsuiteCustomer->externalId = null;
}
// Dispatch event before sending customer to Netsuite
$this->eventManager->dispatch(
'netsuite_customer_send_before',
['netsuite_customer' => $netsuiteCustomer]
);
// Send the customer to Netsuite
// Assuming _getNetsuiteService() and the subsequent Netsuite call are implemented
$response = $this->_getNetsuiteService()->add($netsuiteCustomer);
if ($response->writeResponse->status->isSuccess) {
return $response->writeResponse->baseRef->internalId;
} else {
throw new Exception(json_encode($response->writeResponse->status->statusDetail));
}
}
protected function replaceName($value) {
return preg_replace('/[^\p{L}\p{M}\,\-\_\.\'\s\d]/', ' ', $value);
}
/**
* filter first non-empty value from array and return as array.
*
* @param array $array
* @return array
*/
protected function filterFirstNonEmpty($array) {
foreach ($array as $value) {
if ($value != '') {
$value = $this->replaceName($value);
$value = explode(' ', $value);
return $value;
}
}
return [];
}
/**
* Get name from address text.
*
* @param string $address
* @return array
*/
protected function getNameFromAddressText($address) {
if (empty($address)) {
return [];
}
return $this->filterFirstNonEmpty(explode("\n", $address));
}
/**
* Get customer group ID by name.
*
* @param string $name
* @return int
*/
protected function getCustomerGroupIdByName($name) {
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('customer_group_code', $name)
->create();
try {
$customerGroup = $this->groupRepository->getList($searchCriteria)->getItems();
return array_shift($customerGroup)->getId();
} catch (NoSuchEntityException $e) {
throw new LocalizedException(__("Error fetching customer group ID: %1", $e->getMessage()));
}
}
/**
* get wholesale customer group id.
*
* @return int
*/
protected function getDefaultCustomerGroupId() {
if (!isset($this->customerGroupIdMap[$this->default_customer_group])) {
$this->customerGroupIdMap[$this->default_customer_group] = $this->getCustomerGroupIdByName($this->default_customer_group);
}
return $this->customerGroupIdMap[$this->default_customer_group];
}
/**
* Get region by country code and region code.
*
* @param string $countryCode
* @param string $regionCode
* @return \Magento\Directory\Model\Region
*/
protected function getRegion($countryCode, $regionCode) {
try {
$region = $this->regionFactory->create();
$region->loadByCode($regionCode, $countryCode);
return $region ?? '';
} catch (\Exception $e) {
throw new LocalizedException(__("Error fetching region ID: %1", $e->getMessage()));
}
}
}
+517
View File
@@ -0,0 +1,517 @@
<?php
namespace JR\NetSuite\Mapper;
use JR\NetSuite\Mapper\AbstractMapper;
use Magento\Directory\Model\RegionFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use JR\NetSuite\Mapper\CustomerMapper;
use JR\NetSuite\Api\LocationRepositoryInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Tax\Api\TaxRateRepositoryInterface;
// Handles the specifics of mapping order data.
class OrderMapper
{
const ORDER_STATUS_MAPPER = [
'pendingApproval' => 'pending',
'pendingFulfillment' => 'pending',
'cancelled' => 'canceled',
'partiallyFulfilled' => 'processing',
'pendingBillingPartFulfilled' => 'processing',
'pendingBilling' => 'processing',
'fullyBilled' => 'complete',
'closed' => 'closed',
'undefined' => 'undefined'
];
const SHIP_METHOD_MAPPER = [
'freeshipping_freeshipping' => '911',
'will_call' => '911',
'ups_ups' => '1716'
];
/**
* Shipping method mapping from NetSuite to Magento.
*/
const SHIP_METHOD_MAPPER_R = [
// Will Call
'911' => 'instore_pickup', // Will Call
// UPS
'xxxx' => 'ups_11', // UPS Standard
'1716' => 'ups_03', // UPS® Ground
'7074' => 'ups_59', // UPS 2nd Day Air A.M.
'6849' => 'ups_59', // UPS 2nd Day Air A.M.®
'4622' => 'ups_02', // UPS 2nd Day Air®
'7076' => 'ups_12', // UPS 3 Day Select
'6845' => 'ups_12', // UPS 3 Day Select®
'7077' => 'ups_01', // UPS Next Day Air
'6847' => 'ups_01', // UPS Next Day Air®
'4623' => 'ups_01', // UPS Next Day Air Saver® [***Closest Match***]
'4624' => 'ups_14', // UPS Next Day Air® Early A.M.®
'10720' => 'ups_08', // UPS Worldwide Expedited®
'10721' => 'ups_07', // UPS Worldwide Express®
'xxxxx' => 'ups_54', // UPS Worldwide Express Plus
'10722' => 'ups_65', // UPS Worldwide Saver®
// Fedex (Due to Fedex unavailability, flatrate_flatrate will be used)
'4630' => 'flatrate_flatrate', // 'fedex_FEDEX_2_DAY', // FedEx 2Day®
'4633' => 'flatrate_flatrate', // 'fedex_FEDEX_2_DAY_AM', // FedEx 2Day® A.M.
'4632' => 'flatrate_flatrate', // 'fedex_FEDEX_3_DAY_FREIGHT', // FedEx 3Day® Freight
'4631' => 'flatrate_flatrate', // 'fedex_FEDEX_EXPRESS_SAVER', // FedEx Express Saver®
'4627' => 'flatrate_flatrate', // 'fedex_FIRST_OVERNIGHT', // FedEx First Overnight®
'4634' => 'flatrate_flatrate', // 'fedex_FEDEX_1_DAY_FREIGHT', // FedEx First Overnight® Freight [***Closest Match***]
'1717' => 'flatrate_flatrate', // 'fedex_FEDEX_GROUND', // FedEx Ground®
'4626' => 'flatrate_flatrate', // 'fedex_GROUND_HOME_DELIVERY', // FedEx Home Delivery®
'4636' => 'flatrate_flatrate', // 'fedex_INTERNATIONAL_ECONOMY', // FedEx International Economy®
'4635' => 'flatrate_flatrate', // 'fedex_INTERNATIONAL_PRIORITY', // FedEx International Priority®
'4628' => 'flatrate_flatrate', // 'fedex_PRIORITY_OVERNIGHT', // FedEx Priority Overnight®
'4629' => 'flatrate_flatrate', // 'fedex_STANDARD_OVERNIGHT', // FedEx Standard Overnight®
// Others
'4625' => 'flatrate_flatrate', // USPS/Trucking/International
'7369' => 'flatrate_flatrate' // Customer Provided
];
/**
* @var RegionFactory
*/
protected $regionFactory;
/**
* @var int
*/
protected $storeId;
/**
* @var \JR\NetSuite\Helper\Data
*/
protected $helper;
/**
* @var SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;
/**
* @var CustomerMapper
*/
protected $customerMapper;
/**
* @var LocationRepository
*/
protected $locationRepository;
/**
* @var OrderRepositoryInterface
*/
protected $orderRepository;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @var Product
*/
protected $productModel;
/**
* @var GroupRepositoryInterface
*/
protected $groupRepository;
/**
* @var TaxRateRepositoryInterface
*/
protected $taxRateRepository;
/**
* OrderMapper constructor.
*/
public function __construct(
RegionFactory $regionFactory,
\JR\NetSuite\Helper\Data $helper,
SearchCriteriaBuilder $searchCriteriaBuilder,
CustomerMapper $customerMapper,
LocationRepositoryInterface $locationRepository,
OrderRepositoryInterface $orderRepository,
ProductRepositoryInterface $productRepository,
Product $productModel,
GroupRepositoryInterface $groupRepository,
TaxRateRepositoryInterface $taxRateRepository
) {
$this->regionFactory = $regionFactory;
$this->helper = $helper;
$this->storeId = $this->helper->getDefaultStoreId();
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->customerMapper = $customerMapper;
$this->locationRepository = $locationRepository;
$this->orderRepository = $orderRepository;
$this->productRepository = $productRepository;
$this->productModel = $productModel;
$this->groupRepository = $groupRepository;
$this->taxRateRepository = $taxRateRepository;
}
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
public function convertToMagentoFormat($netSuiteData)
{
// convert netsuite data to magento data
$magentoData = [];
foreach ($netSuiteData as $data) {
$convertedData = [
'netsuite_order_location_id' => $data['location'],
'netsuite_order_id' => $data['internalid'],
'netsuite_order_number' => $data['tranid'],
'netsuite_customer_id' => $data['entity'],
'store_id' => $this->storeId,
'email' => $data['email'],
'company' => $data['companyname'],
'status' => self::ORDER_STATUS_MAPPER[$data['status']] ?? 'undefined',
'total' => $data['total'],
'amount' => $data['amount'],
'tax' => $data['taxtotal'],
'shipping_amount' => $data['shippingcost'],
'shipping_description' => $data['shipcarrier'],
'shipping_method' => $data['shipmethod'],
'purchase_date' => $data['datecreated'],
'last_modified_date' => $data['lastmodifieddate'],
'other_ref_num' => $data['otherrefnum'],
];
if ($data['customer'] ?? false) {
$convertedData['customer'] = $this->customerMapper->convertToMagentoFormat([$data['customer']]);
$convertedData['customer'] = reset($convertedData['customer']);
}
// billing address
if ($data['billaddress'] != '') {
$billaddressee = $this->filterFirstNonEmpty([
$data['billattention'],
$data['billaddressee'],
]);
if (empty($billaddressee)) {
$billaddressee = $this->getNameFromAddressText($data['billaddress']);
}
$convertedData['billing_address'] = [
'firstname' => $convertedData['customer']['billing_address']['firstname'] ??
$convertedData['customer']['shipping_address']['firstname'] ??
(count($billaddressee) > 0 ? array_shift($billaddressee) : ''),
'lastname' => $convertedData['customer']['billing_address']['lastname'] ??
$convertedData['customer']['shipping_address']['lastname'] ??
(count($billaddressee) > 0 ? implode(' ', $billaddressee) : $data['companyname']),
'company' => $data['companyname'],
'street' => [!empty($data['billaddress1']) ? $data['billaddress1'] : '-', $data['billaddress2']],
'city' => $data['billcity'],
'country_id' => $data['billcountry'],
'region_id' => $this->getRegion($data['billcountry'], $data['billstate'])->getId(),
'postcode' => !empty($data['billzip']) ? $data['billzip'] : '-' ,
'telephone' => $data['billphone'],
'fax' => '',
'save_in_address_book' => 0
];
}
if ($data['shipaddress'] != '') {
$shipaddressee = $this->filterFirstNonEmpty([
$data['shipattention'],
$data['shipaddressee'],
]);
if (empty($shipaddressee)) {
$shipaddressee = $this->getNameFromAddressText($data['shipaddress']);
}
$convertedData['shipping_address'] = [
'firstname' => $convertedData['customer']['shipping_address']['firstname'] ??
$convertedData['customer']['billing_address']['firstname'] ??
(count($shipaddressee) > 0 ? array_shift($shipaddressee) : ''),
'lastname' => $convertedData['customer']['shipping_address']['lastname'] ??
$convertedData['customer']['billing_address']['lastname'] ??
(count($shipaddressee) > 0 ? implode(' ', $shipaddressee) : $data['companyname']),
'company' => $data['companyname'],
'street' => [!empty($data['shipaddress1']) ? $data['shipaddress1'] : '-', $data['shipaddress2']],
'city' => $data['shipcity'],
'country_id' => $data['shipcountry'],
'region_id' => $this->getRegion($data['shipcountry'], $data['shipstate'])->getId(),
'postcode' => $data['shipzip'],
'telephone' => $data['shipphone'],
'fax' => '',
'save_in_address_book' => 0
];
if (
isset($convertedData['shipping_address'])
&& !empty($convertedData['shipping_address']['firstname'])
&& ($convertedData['shipping_address']['firstname'][0] ?? '' == $convertedData['shipping_address']['street'][0][0] ?? '')
&& isset($convertedData['billing_address'])
) {
$convertedData['shipping_address']['firstname'] = $convertedData['billing_address']['firstname'];
$convertedData['shipping_address']['lastname'] = $convertedData['billing_address']['lastname'];
}
}
// item
$convertedData['items'] = [];
foreach ($data['items'] as $item) {
$convertedData['items'][] = [
'netsuite_order_item_id' => $item['itemId'],
'sku' => $item['itemText'],
'description' => $item['description'],
'qty' => $item['quantity'],
'type' => $item['type'],
'price' => $item['rate'],
'amount' => $item['amount'],
];
}
// payment
$convertedData['payment'] = [
'method' => $data['paymentmethod'],
'paid_amount' => $data['paidamount'],
'date_paid' => $data['paymenteventdate'],
'status' => $data['paymenteventresult'],
'type' => $data['paymenteventtype'],
// 'cc_type' => '',
// 'cc_number_enc' => '',
// 'cc_last4' => '',
// 'cc_owner' => '',
// 'cc_exp_month' => '',
// 'cc_exp_year' => '',
// 'cc_ss_start_month' => '',
// 'cc_ss_start_year' => '',
// 'cc_ss_issue' => '',
];
$magentoData[] = $convertedData;
}
return $magentoData;
}
/**
* Convert data from Magento format to NetSuite format.
*
* @param \Magento\Sales\Model\Order $order
* @return array
*/
public function convertToNetSuiteFormat($order)
{
$data = $this->initializeData($order);
$data['items'] = $this->getOrderItems($order);
return $data;
}
/**
* Initialize variables.
*
* @param \Magento\Sales\Model\Order $order
* @param string $netsuiteCustomerId
* @return array
*/
protected function initializeData($order, $netsuiteCustomerId = '')
{
$shippingAddress = $order->getShippingAddress();
$billingAddress = $order->getBillingAddress();
$phone = preg_replace('/[^0-9]/', '', $shippingAddress->getTelephone());
if (strlen($phone) == 10) {
$phone = '0001' . $phone;
}
$phone = str_pad($phone, 14, '0', STR_PAD_LEFT);
try {
$region = $this->regionFactory->create();
$region->loadByName($shippingAddress->getRegion(), $shippingAddress->getCountryId());
} catch (\Exception $e) {
$region = null;
}
$address = [
'country' => $shippingAddress->getCountryId(),
'city' => $shippingAddress->getCity(),
'state' => $region?->getCode() ?? '',
'zip' => $shippingAddress->getPostcode(),
'addressee' => $shippingAddress->getCompany(),
'attention' => $shippingAddress->getFirstname() . ' ' . $shippingAddress->getLastname(),
'addrphone' => $phone,
'addr1' => $shippingAddress->getStreetLine(1),
'addr2' => $shippingAddress->getStreetLine(2),
];
$payment = $order->getPayment();
$cardInfo = [
'Card #' => '******' . $payment->getCcLast4(),
'Billing address' => implode(', ', array_filter($billingAddress->getStreet())) . ', ' . $billingAddress->getCity() . ', ' . $billingAddress->getRegionCode() . ' ' . $billingAddress->getPostcode() . ', ' . $billingAddress->getCountryId(),
'Card Holder Name' => $billingAddress->getFirstname() . ' ' . $billingAddress->getLastname(),
];
$cardInfo = implode("\n", array_map(function ($key, $value) {
return $key . ': ' . $value;
}, array_keys($cardInfo), $cardInfo));
$phone = preg_replace('/[^0-9]/', '', $shippingAddress->getTelephone() ?? '');
$phone = substr($phone, strlen($phone) - 10, 10);
// get location id based on shipping address
$locationId = $this->getLocationId($shippingAddress->getCity());
if (!$locationId) {
$locationId = $this->getLocationId($region?->getCode() ?? '');
}
$vars = [
'note' => $order->getCustomerNote() ?? '',
'address' => $address,
'orderNo' => $order->getIncrementId(),
'cardInfo' => $cardInfo,
'terms' => '12',
'phone' => $phone,
'custId' => $netsuiteCustomerId, // TODO: get customer ID from NetSuite
'company' => $order->getBillingAddress()->getCompany(),
'location' => '222', // TODO: get location from config
'shipmethod' => self::SHIP_METHOD_MAPPER[$order->getShippingMethod()],
'shippingcost' => $order->getShippingAmount(),
// TODO: get entity from NetSuite
// 'entity' => $netsuiteEntityId,
'email' => $order->getCustomerEmail(),
// 'customer' => $this->customerMapper->convertToNetSuiteFormatByEmail($order->getCustomerEmail()),
];
if ($order->getDiscountAmount() < 0) {
$vars['discountItem'] = $order->getDiscountAmount();
$vars['discountRate'] = round(($order->getDiscountAmount() / $order->getGrandTotal()) * 100, 2);
}
return $vars;
}
/**
* search location list by name
*/
protected function getLocationId($name)
{
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('is_active', 1)
->addFilter('name', $name)
->create();
$locations = $this->locationRepository->getList($searchCriteria)->getItems();
if (count($locations) > 0) {
$location = reset($locations);
return $location->getLocationId() ?? '';
}
return '';
}
/**
* get order by field and value.
*
* @param string $field
* @return \Magento\Sales\Model\Order | null
*/
public function getOrderBy($field, $value)
{
$searchCriteria = $this->searchCriteriaBuilder
->addFilter($field, $value)
->create();
$orders = $this->orderRepository->getList($searchCriteria)->getItems();
$order = count($orders) > 0 ? reset($orders) : null;
return $order;
}
/**
* Get order items.
*
* @param \Magento\Sales\Model\Order $order
* @return array
*/
protected function getOrderItems($order)
{
$items = [];
foreach ($order->getAllItems() as $item) {
$product = $this->productModel->load($item->getProductId());
$items[] = [
'id' => $product->getCustomAttribute('netsuite_id')?->getValue() ?? '',
'quantity' => $item->getQtyOrdered(),
'rate' => $item->getPrice(),
];
}
return $items;
}
/**
* filter first non-empty value from array and return as array.
*
* @param array $array
* @return array
*/
protected function filterFirstNonEmpty($array)
{
foreach ($array as $value) {
if ($value != '') {
$value = preg_replace('/[^\p{L}\p{M}\,\-\_\.\'\s\d]/', ' ', $value);
$value = explode(' ', $value);
return $value;
}
}
return [];
}
/**
* Get name from address text.
*
* @param string $address
* @return array
*/
protected function getNameFromAddressText($address)
{
if (empty($address)) {
return [];
}
return $this->filterFirstNonEmpty(explode("\n", $address));
}
/**
* Get region by country code and region code.
*
* @param string $countryCode
* @param string $regionCode
* @return \Magento\Directory\Model\Region
*/
protected function getRegion($countryCode, $regionCode)
{
try {
$region = $this->regionFactory->create();
$region->loadByCode($regionCode, $countryCode);
return $region;
} catch (\Exception $e) {
throw new LocalizedException(__("Error fetching region ID: %1", $e->getMessage()));
}
}
/**
* Convert a given NetSuite shipping method to a corresponding Magento shipping method.
* If the given NetSuite shipping method does not exist in the mapping, 'flatrate_flatrate'
* will be returned.
*
* @param string $nsShipMethod NetSuite ship method internal ID.
* @return string
*/
public function parseNetSuiteShippingMethod($nsShipMethod)
{
if (array_key_exists($nsShipMethod, self::SHIP_METHOD_MAPPER_R)) {
return self::SHIP_METHOD_MAPPER_R[$nsShipMethod];
}
return 'flatrate_flatrate';
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace JR\NetSuite\Mapper;
use JR\NetSuite\Mapper\AbstractMapper;
// Handles the specifics of mapping product data.
class ProductMapper {
/**
* ProductMapper constructor.
*/
public function __construct(
) {
}
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
public function convertToMagentoFormat($netSuiteData) {
// convert netsuite data to magento data
$magentoData = [];
foreach($netSuiteData as $data) {
$magentoData[] = [
'netsuite_product_id' => $data['internalid'],
'sku' => $data['itemid'],
// 'type' => $data['includechildren'] ? 'configurable' : 'simple',
// 'category' => $data['category'],
'name' => $data['displayname'] == '' ? $data['itemid'] : $data['displayname'],
'description' => $data['salesdescription'],
'status' => $data['isinactive'],
// 'vendor' => $data['vendor'],
// 'manufacturer' => $data['manufacturer'],
'upc' => $data['upccode'],
// 'mpn' => $data['mpn'],
// 'tax_class' => $data['taxschedule'],
'weight' => $data['weight'] ?? 1,
// 'weight_unit' => $data['weightunit'],
// 'cost' => $data['cost'],
'price' => $data['baseprice'] != '' ? $data['baseprice'] : 0,
'qty' => (int) ($data['locationquantityavailable'] ?? $data['quantityavailable'] ?? 0),
'locationId' => $data['inventorylocation'] ?? '',
'custitem_item_eol_for_sales' => $data['custitem_item_eol_for_sales'] ?? false,
// 'is_in_stock' => ($data['quantityavailable'] ?? 0) > 0 ? 1 : 0,
// 'created_at' => $data['createddate'],
// 'updated_at' => $data['lastmodifieddate']
];
}
return $magentoData;
}
/**
* Convert data from Magento format to NetSuite format.
*
* @param array $magentoData
* @return array
*/
public function convertToNetSuiteFormat($magentoData) {
// Your conversion logic here
}
}
+229
View File
@@ -0,0 +1,229 @@
<?php
namespace JR\NetSuite\Mapper;
use JR\NetSuite\Mapper\AbstractMapper;
use JR\NetSuite\Helper\Data as Helper;
use Magento\Catalog\Api\ProductRepositoryInterface;
use \Mirasvit\Rma\Api\Repository\RmaRepositoryInterface;
use \Mirasvit\Rma\Api\Service\Rma\RmaManagementInterface;
use \Mirasvit\Rma\Api\Service\Item\ItemListBuilderInterface;
use \Mirasvit\Rma\Api\Service\Item\ItemManagementInterface;
// Handles the specifics of mapping rma data.
class RmaMapper
{
public const STATUS_MAP = [
'pending-approval' => 'pending',
'Pending-receipt' => 'pending',
'partially-received' => 'pending',
'pending-refund/partially-received' => 'pending',
'pending-refund' => 'pending',
'refunded' => 'refunded',
'cancelled' => 'closed',
'closed' => 'closed',
'pendingApproval' => 'pending',
'pendingReceipt' => 'pending',
'partiallyReceived' => 'pending',
'pendingRefund/partiallyReceived' => 'pending',
'pendingRefund' => 'pending',
];
/**
* @var Helper
*/
protected $helper;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @var RmaRepositoryInterface
*/
protected $rmaRepository;
/**
* @var RmaManagementInterface
*/
protected $rmaManagement;
/**
* @var ItemListBuilderInterface
*/
protected $itemListBuilder;
/**
* @var ItemManagementInterface
*/
protected $itemManagement;
/**
* @var \JR\NetSuite\Mapper\CustomerMapper
*/
private $customerMapper;
/**
* RmaMapper constructor.
*
* @param RmaRepositoryInterface $rmaRepository
* @return void
*/
public function __construct(
Helper $helper,
ProductRepositoryInterface $productRepository,
RmaRepositoryInterface $rmaRepository,
RmaManagementInterface $rmaManagement,
ItemListBuilderInterface $itemListBuilder,
ItemManagementInterface $itemManagement,
\JR\NetSuite\Mapper\CustomerMapper $customerMapper
) {
$this->helper = $helper;
$this->productRepository = $productRepository;
$this->rmaRepository = $rmaRepository;
$this->rmaManagement = $rmaManagement;
$this->itemListBuilder = $itemListBuilder;
$this->itemManagement = $itemManagement;
$this->customerMapper = $customerMapper;
}
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
public function convertToMagentoFormat($netSuiteData)
{
// convert netsuite data to magento data
$magentoData = [];
foreach ($netSuiteData as $data) {
$magentoData[] = [
'netsuite_id' => $data['internalid'],
'netsuite_tran_id' => $data['tranid'],
'recorded_at' => $data['datecreated'],
'netsuite_order_id' => $data['createdfrom'],
'netsuite_order_number' => $data['custbody_sales_order'],
'transaction_date' => $data['trandate'],
'status' => self::STATUS_MAP[$data['status']] ?? 'pending',
'customer' => $this->customerMapper->convertToMagentoFormat([$data['customer']])[0] ?? [],
'billaddress' => $data['billaddress'],
'billaddress1' => $data['billaddress1'],
'billaddress2' => $data['billaddress2'],
'billcity' => $data['billcity'],
'billcountry' => $data['billcountry'],
'billstate' => $data['billstate'],
'billzip' => $data['billzip'],
'billphone' => $data['billphone'],
'shipaddress' => $data['shipaddress'],
'shipaddress1' => $data['shipaddress1'],
'shipaddress2' => $data['shipaddress2'],
'shipcity' => $data['shipcity'],
'shipcountry' => $data['shipcountry'],
'shipstate' => $data['shipstate'],
'shipzip' => $data['shipzip'],
'shipphone' => $data['shipphone'],
'total' => $data['total'],
'taxtotal' => $data['taxtotal'],
'shippingcost' => $data['shippingcost'],
'discountamount' => $data['discountamount'],
'amount' => $data['amount'],
'location' => $data['location'],
'return_address' => $data['custbody_return_address_proxy'],
'notes' => $data['custbody_notes'],
'internal_notes' => $data['custbody_internal_notes'],
'items' => $this->convertItems($data),
];
}
return $magentoData;
}
/**
* Convert items from NetSuite format to Magento format.
*
* @param array $data
* @return array
*/
protected function convertItems($data)
{
$items = $data['items'];
$result = [];
foreach ($items as $item) {
$result[] = [
'sku' => $item['itemText'],
'netsuite_id' => $item['itemId'],
'name' => $item['itemText'],
'type' => $item['type'],
'description' => $item['description'],
'qty' => $item['quantity'],
'qty_billed' => $item['quantitybilled'],
'reason' => $item['reasonCode'],
'condition' => $item['conditions'],
'resolution' => $data['custbody_request_type'],
'rate' => $item['rate'],
'amount' => $item['amount'],
'discountamount' => $item['discountamount'],
];
}
return $result;
}
/**
* Convert data from Magento format to NetSuite format.
*
* @param string $rmaId
* @return array
*/
public function convertToNetSuiteFormat($rmaId)
{
$rma = $this->rmaRepository->get($rmaId);
$order = $this->rmaManagement->getOrder($rma);
$customer = $this->rmaManagement->getCustomer($rma);
$result = [
'orderId' => $order->getNetsuiteId(),
'createdAt' => $this->helper->convertLocalTimeToUtc($rma->getCreatedAt(), 'm/d/Y'),
'status' => $this->rmaManagement->getStatus($rma)->getCode(),
'customerId' => $customer->getNetsuiteId(),
'items' => $this->getRmaItems($rma),
];
return $result;
}
/**
* Get RMA items.
*
* @param RmaInterface $rma
* @return array
*/
protected function getRmaItems($rma)
{
$items = $this->itemListBuilder->getRmaItems($rma);
$result = [];
foreach ($items as $item) {
if (!$item->getQtyRequested()) {
continue;
}
$orderItem = $this->itemManagement->getOrderItem($item);
$product = $this->productRepository->getById($orderItem->getProductId());
$result[] = [
'id' => $product->getCustomAttribute('netsuite_id')?->getValue() ?? '',
'sku' => $product->getSku(),
'reason' => $this->itemManagement->getReasonName($item),
'condition' => $this->itemManagement->getConditionName($item),
'resolution' => $this->itemManagement->getResolutionName($item),
'rate' => $orderItem->getPrice(),
'qty' => $item->getQtyRequested(),
'amount' => $orderItem->getPrice() * $item->getQtyRequested(),
'tax_percent' => $orderItem->getTaxPercent(),
'tax_amount' => $orderItem->getTaxPercent() / 100 * $orderItem->getPrice() * $item->getQtyRequested(),
];
}
return $result;
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
namespace JR\NetSuite\Model\Config\Source;
class Category implements \Magento\Framework\Option\ArrayInterface
{
private $categoryFactory;
private $categoryCollectionFactory;
public function __construct(
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
) {
$this->categoryFactory = $categoryFactory;
$this->categoryCollectionFactory = $categoryCollectionFactory;
}
public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
{
$collection = $this->categoryCollectionFactory->create();
$collection->addAttributeToSelect('*');
// select only active categories
if ($isActive) {
$collection->addIsActiveFilter();
}
// select categories of certain level
if ($level) {
$collection->addLevelFilter($level);
}
// sort categories by some value
if ($sortBy) {
$collection->addOrderField($sortBy);
}
// select certain number of categories
if ($pageSize) {
$collection->setPageSize($pageSize);
}
return $collection;
}
public function toOptionArray()
{
$arr = $this->_toArray();
$ret = [];
foreach ($arr as $key => $value) {
$ret[] = [
'value' => $key,
'label' => $value
];
}
return $ret;
}
private function _toArray()
{
$categories = $this->getCategoryCollection(true, false, false, false);
$categoryList = [];
foreach ($categories as $category) {
$categoryList[$category->getEntityId()] = __($this->_getParentName($category->getPath()) . $category->getName());
}
return $categoryList;
}
private function _getParentName($path = '')
{
$parentName = '';
$rootCats = [1,2];
$catTree = explode("/", $path);
// Deleting category itself
array_pop($catTree);
if ($catTree && (count($catTree) > count($rootCats))) {
foreach ($catTree as $catId) {
if (!in_array($catId, $rootCats)) {
$category = $this->categoryFactory->create()->load($catId);
$categoryName = $category->getName();
$parentName .= $categoryName . ' -> ';
}
}
}
return $parentName;
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace JR\NetSuite\Model\Config\Source;
class CustomerGroup
{
protected $_customerGroupCollectionFactory;
public function __construct(
\Magento\Customer\Model\ResourceModel\Group\CollectionFactory $customerGroupCollectionFactory
) {
$this->_customerGroupCollectionFactory = $customerGroupCollectionFactory;
}
public function toOptionArray()
{
$customerGroups = $this->_customerGroupCollectionFactory->create();
$customerGroupArray = [];
foreach ($customerGroups as $customerGroup) {
$customerGroupArray[] = [
'value' => $customerGroup->getCode(),
'label' => $customerGroup->getCode()
];
}
return $customerGroupArray;
}
}
@@ -0,0 +1,72 @@
<?php
namespace JR\NetSuite\Model\Config\Source;
use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;
use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface;
use Magento\Framework\Data\OptionSourceInterface;
use Magento\InventoryApi\Api\SourceRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
class InventorySource extends AbstractSource implements SourceInterface, OptionSourceInterface
{
protected $sourceRepository;
protected $searchCriteriaBuilder;
public function __construct(
SourceRepositoryInterface $sourceRepository,
SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->sourceRepository = $sourceRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
/**
* Retrieve option array
*
* @return string[]
*/
public function getOptionArray()
{
$searchCriteria = $this->searchCriteriaBuilder->create();
$sources = $this->sourceRepository->getList($searchCriteria)->getItems();
$options = [];
foreach ($sources as $source) {
$options[$source->getSourceCode()] = $source->getName();
}
return $options;
}
/**
* Get options
*
* @return array
*/
public function getAllOptions()
{
$searchCriteria = $this->searchCriteriaBuilder->create();
$sources = $this->sourceRepository->getList($searchCriteria)->getItems();
$options = [];
foreach ($sources as $source) {
$options[] = [
'value' => $source->getSourceCode(),
'label' => $source->getName()
];
}
return $options;
}
/**
* Retrieve option text by option value
*
* @return array
*/
public function toOptionArray()
{
return $this->getAllOptions();
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace JR\NetSuite\Model\Config\Source;
use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;
use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface;
use Magento\Framework\Data\OptionSourceInterface;
/**
* Product status functionality model
*
* @api
* @since 100.0.2
*/
class IsActive extends AbstractSource implements SourceInterface, OptionSourceInterface
{
/**#@+
* Product Status values
*/
const STATUS_ENABLED = 1;
const STATUS_DISABLED = 0;
/**#@-*/
/**
* Retrieve Visible Status Ids
*
* @return int[]
*/
public function getVisibleStatusIds()
{
return [self::STATUS_ENABLED];
}
/**
* Retrieve Saleable Status Ids
* Default Product Enable status
*
* @return int[]
*/
public function getSaleableStatusIds()
{
return [self::STATUS_ENABLED];
}
/**
* Retrieve option array
*
* @return string[]
*/
public function getOptionArray()
{
return [self::STATUS_ENABLED => __('Enabled'), self::STATUS_DISABLED => __('Disabled')];
}
/**
* Retrieve option array with empty value
*
* @return string[]
*/
public function getAllOptions()
{
$result = [];
foreach (self::getOptionArray() as $index => $value) {
$result[] = ['value' => $index, 'label' => $value];
}
return $result;
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace JR\NetSuite\Model\Config\Source;
use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;
use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface;
use Magento\Framework\Data\OptionSourceInterface;
/**
* Product status functionality model
*
* @api
* @since 100.0.2
*/
class Status extends AbstractSource implements SourceInterface, OptionSourceInterface
{
/**#@+
* Product Status values
*/
const STATUS_PENDING = 'pending';
const STATUS_PROCESSING = 'processing';
const STATUS_SUCCESS = 'success';
const STATUS_FAILED = 'failed';
const STATUS_ERROR = 'error';
/**#@-*/
/**
* Retrieve Visible Status Ids
*
* @return string[]
*/
public function getVisibleStatusIds()
{
return [self::STATUS_SUCCESS];
}
/**
* Retrieve Saleable Status Ids
* Default Product Enable status
*
* @return string[]
*/
public function getSaleableStatusIds()
{
return [self::STATUS_SUCCESS];
}
/**
* Retrieve option array
*
* @return string[]
*/
public function getOptionArray()
{
return [
self::STATUS_PENDING => __('Pending'),
self::STATUS_ERROR => __('Error'),
self::STATUS_FAILED => __('Failed'),
self::STATUS_PROCESSING => __('Processing'),
self::STATUS_SUCCESS => __('Success'),
];
}
/**
* Retrieve option array with empty value
*
* @return string[]
*/
public function getAllOptions()
{
$result = [];
foreach (self::getOptionArray() as $index => $value) {
$result[] = ['value' => $index, 'label' => $value];
}
return $result;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace JR\NetSuite\Model\Config\Source;
class Store
{
protected $_storeManager;
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
$this->_storeManager = $storeManager;
}
public function toOptionArray()
{
$stores = $this->_storeManager->getStores();
$options = [];
foreach ($stores as $store) {
$options[] = [
'label' => $store->getName(),
'value' => $store->getId()
];
}
return $options;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace JR\NetSuite\Model\Config\Source;
class Taxclass implements \Magento\Framework\Option\ArrayInterface
{
protected $taxClass;
public function __construct(
\Magento\Tax\Model\TaxClass\Source\Product $taxClass
) {
$this->taxClass = $taxClass;
}
/**
* @return array
*/
public function toOptionArray()
{
return $this->taxClass->getAllOptions();
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace JR\NetSuite\Model\Config\Source;
class Visibility implements \Magento\Framework\Option\ArrayInterface
{
protected $visibility;
public function __construct(
\Magento\Catalog\Model\Product\Visibility $visibility
) {
$this->visibility = $visibility;
}
/**
* @return array
*/
public function toOptionArray()
{
return $this->visibility->getOptionArray();
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace JR\NetSuite\Model;
use Magento\Framework\Model\AbstractModel;
class CustomerQueue extends AbstractModel
{
public function _construct()
{
$this->_init(\JR\NetSuite\Model\ResourceModel\CustomerQueue::class);
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace JR\NetSuite\Model\Data;
use Magento\Framework\Model\AbstractModel;
use JR\NetSuite\Service\ProductsSyncService;
use JR\NetSuite\Mapper\ProductMapper;
use JR\NetSuite\Model\ResourceModel\ProductQueue as QueueResource;
class ProductQueueItem extends AbstractModel
{
/**
* @var ProductsSyncService
*/
protected $productSyncService;
/**
* @var ProductMapper
*/
protected $productMapper;
public function _construct(
) {
$this->_init(QueueResource::class);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace JR\NetSuite\Model;
use Magento\Framework\Model\AbstractModel;
class Location extends AbstractModel
{
public function _construct()
{
$this->_init(\JR\NetSuite\Model\ResourceModel\Location::class);
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Model\Location;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Ui\DataProvider\AbstractDataProvider;
use JR\NetSuite\Model\ResourceModel\Location\CollectionFactory;
class DataProvider extends AbstractDataProvider
{
/**
* @var array
*/
protected $loadedData;
/**
* @inheritDoc
*/
protected $collection;
/**
* @var DataPersistorInterface
*/
protected $dataPersistor;
/**
* @param string $name
* @param string $primaryFieldName
* @param string $requestFieldName
* @param CollectionFactory $collectionFactory
* @param DataPersistorInterface $dataPersistor
* @param array $meta
* @param array $data
*/
public function __construct(
$name,
$primaryFieldName,
$requestFieldName,
CollectionFactory $collectionFactory,
DataPersistorInterface $dataPersistor,
array $meta = [],
array $data = []
) {
$this->collection = $collectionFactory->create();
$this->dataPersistor = $dataPersistor;
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
}
/**
* @inheritDoc
*/
public function getData()
{
if (isset($this->loadedData)) {
return $this->loadedData;
}
$items = $this->collection->getItems();
foreach ($items as $model) {
$this->loadedData[$model->getId()] = $model->getData();
}
$data = $this->dataPersistor->get('jr_netsuite_location');
if (!empty($data)) {
$model = $this->collection->getNewEmptyItem();
$model->setData($data);
$this->loadedData[$model->getId()] = $model->getData();
$this->dataPersistor->clear('jr_netsuite_location');
}
return $this->loadedData;
}
}
+152
View File
@@ -0,0 +1,152 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace JR\NetSuite\Model;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use JR\NetSuite\Api\Data\LocationInterface;
use JR\NetSuite\Api\Data\LocationInterfaceFactory;
use JR\NetSuite\Api\Data\LocationSearchResultsInterfaceFactory;
use JR\NetSuite\Api\LocationRepositoryInterface;
use JR\NetSuite\Model\ResourceModel\Location as ResourceLocation;
use JR\NetSuite\Model\ResourceModel\Location\CollectionFactory as LocationCollectionFactory;
class LocationRepository implements LocationRepositoryInterface
{
/**
* @var LocationInterfaceFactory
*/
protected $locationFactory;
/**
* @var CollectionProcessorInterface
*/
protected $collectionProcessor;
/**
* @var Location
*/
protected $searchResultsFactory;
/**
* @var ResourceLocation
*/
protected $resource;
/**
* @var LocationCollectionFactory
*/
protected $locationCollectionFactory;
/**
* @param ResourceLocation $resource
* @param LocationInterfaceFactory $locationFactory
* @param LocationCollectionFactory $locationCollectionFactory
* @param LocationSearchResultsInterfaceFactory $searchResultsFactory
* @param CollectionProcessorInterface $collectionProcessor
*/
public function __construct(
ResourceLocation $resource,
LocationInterfaceFactory $locationFactory,
LocationCollectionFactory $locationCollectionFactory,
LocationSearchResultsInterfaceFactory $searchResultsFactory,
CollectionProcessorInterface $collectionProcessor
) {
$this->resource = $resource;
$this->locationFactory = $locationFactory;
$this->locationCollectionFactory = $locationCollectionFactory;
$this->searchResultsFactory = $searchResultsFactory;
$this->collectionProcessor = $collectionProcessor;
}
/**
* @inheritDoc
*/
public function save(LocationInterface $location)
{
try {
$this->resource->save($location);
} catch (\Exception $exception) {
throw new CouldNotSaveException(
__(
'Could not save the location: %1',
$exception->getMessage()
)
);
}
return $location;
}
/**
* @inheritDoc
*/
public function get($locationId)
{
$location = $this->locationFactory->create();
$this->resource->load($location, $locationId);
if (!$location->getId()) {
throw new NoSuchEntityException(__('location with id "%1" does not exist.', $locationId));
}
return $location;
}
/**
* @inheritDoc
*/
public function getList(
\Magento\Framework\Api\SearchCriteriaInterface $criteria
) {
$collection = $this->locationCollectionFactory->create();
$this->collectionProcessor->process($criteria, $collection);
$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($criteria);
$items = [];
foreach ($collection as $model) {
$items[] = $model;
}
$searchResults->setItems($items);
$searchResults->setTotalCount($collection->getSize());
return $searchResults;
}
/**
* @inheritDoc
*/
public function delete(LocationInterface $location)
{
try {
$locationModel = $this->locationFactory->create();
$this->resource->load($locationModel, $location->getLocationId());
$this->resource->delete($locationModel);
} catch (\Exception $exception) {
throw new CouldNotDeleteException(
__(
'Could not delete the location: %1',
$exception->getMessage()
)
);
}
return true;
}
/**
* @inheritDoc
*/
public function deleteById($locationId)
{
return $this->delete($this->get($locationId));
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace JR\NetSuite\Model;
use Magento\Framework\Model\AbstractModel;
class OrderQueue extends AbstractModel
{
public function _construct()
{
$this->_init(\JR\NetSuite\Model\ResourceModel\OrderQueue::class);
}
}
+174
View File
@@ -0,0 +1,174 @@
<?php
namespace JR\NetSuite\Model\Queue;
use JR\NetSuite\Helper\Data as Helper;
use JR\NetSuite\Logger\Logger;
use JR\NetSuite\Lib\NetSuiteAPI;
use JR\NetSuite\Mapper\OrderMapper;
use JR\NetSuite\Mapper\CustomerMapper;
use JR\NetSuite\Service\OrdersSyncService;
use JR\NetSuite\Service\CustomersSyncService;
use JR\NetSuite\Queue\CustomerQueueManager;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Framework\Serialize\Serializer\Json;
class Consumer
{
const SUCCESS_RESULT = 200;
/**
* @var NetSuiteAPI
*/
protected $netSuiteAPI;
/**
* @var Logger
*/
protected $logger;
/**
* @var Json
*/
protected $json;
/**
* @var Helper
*/
protected $helper;
/**
* @var OrderMapper
*/
protected $orderMapper;
/**
* @var CustomerMapper
*/
protected $customerMapper;
/**
* @var OrdersSyncService
*/
protected $ordersSyncService;
/**
* @var CustomersSyncService
*/
protected $customersSyncService;
/**
* @var CustomerQueueManager
*/
protected $customerQueueManager;
/**
* @var OrderRepositoryInterface
*/
protected $orderRepository;
/**
* @param Helper $helper
* @param Logger $logger
* @param Json $json
* @param NetSuiteAPI $netSuiteAPI
* @param OrderMapper $orderMapper
* @param CustomerMapper $customerMapper
* @param OrdersSyncService $ordersSyncService
* @param CustomersSyncService $customersSyncService
* @param CustomerQueueManager $customerQueueManager
* @param OrderRepositoryInterface $orderRepository
* @return void
*/
public function __construct(
Helper $helper,
Logger $logger,
Json $json,
NetSuiteAPI $netSuiteAPI,
OrderMapper $orderMapper,
CustomerMapper $customerMapper,
OrdersSyncService $ordersSyncService,
CustomersSyncService $customersSyncService,
CustomerQueueManager $customerQueueManager,
OrderRepositoryInterface $orderRepository,
) {
$this->helper = $helper;
$this->logger = $logger;
$this->json = $json;
$this->netSuiteAPI = $netSuiteAPI;
$this->orderMapper = $orderMapper;
$this->customerMapper = $customerMapper;
$this->ordersSyncService = $ordersSyncService;
$this->customersSyncService = $customersSyncService;
$this->customerQueueManager = $customerQueueManager;
$this->orderRepository = $orderRepository;
}
/**
* Run process from queue
*
* @param $data
* @return void
* @throws \Exception
*/
public function process($data) : void
{
// checking if the module is enabled
if ($this->helper->getNetSuiteIsEnabled()) {
// run process from queue and send request
$data = $this->json->unserialize($data);
// check if the order is already synced
$order = $this->orderMapper->getOrderBy('increment_id', $data["order_id"]);
if (!$order) {
throw new \Exception('Order with #' . $data["order_id"] .' not found');
}
if ($order->getNetSuiteId()) {
return;
}
$filter = ['filter' => ['email', 'is', $data["customer_email"]]];
$result = $this->netSuiteAPI->fetchCustomersWithFilter(1, 1, $filter);
if (!empty($result['error'])) {
throw new \Exception('Error while fetching customer data: ' . $result['message']);
}
// customer is not found
if (empty($result['data'])) {
$this->logger->info("JR Netsuite Model Queue Consumer: Order " . $data["order_id"] . " Customer " . $data["customer_email"] . " not found");
return;
// map customer data
$mapCustomerData = $this->customerMapper->convertToNetSuiteFormatByEmail($data["customer_email"]);
// update customer data to NetSuite
$result = $this->netSuiteAPI->updateCustomer($mapCustomerData);
if ($result['code'] == self::SUCCESS_RESULT) {
$netsuiteCustomerId = $result['data']['internal_id'];
// save the customer Id
$this->customersSyncService->saveNetsuiteId($data["customer_email"], $netsuiteCustomerId);
} else {
throw new \Exception('Error while updating customer data: ' . $result['msg']);
}
} else {
$netsuiteCustomerId = $result['data'][0]['internalid'];
}
// map order data
$mapOrderData = $this->orderMapper->convertToNetSuiteFormat($order);
// $this->logger->info('Map Order Data: ' . $this->json->serialize($mapOrderData));
$mapOrderData['entity'] = $netsuiteCustomerId;
$result = $this->netSuiteAPI->updateOrder($mapOrderData);
// update order status in case of successful result
if ($result['code'] == self::SUCCESS_RESULT) {
// save the order Id
$this->ordersSyncService->saveNetsuiteId($order, $result['data']['internal_id']);
} else {
throw new \Exception('Error while updating order data: ' . $result['msg']);
}
}
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace JR\NetSuite\Model\Queue;
use Magento\Framework\MessageQueue\PublisherInterface;
class OrderToQueue
{
const TOPIC_NAME = 'jr.queue.order';
/**
* @var \Magento\Framework\MessageQueue\PublisherInterface
*/
protected $publisher;
/**
* @param PublisherInterface $publisher
*/
public function __construct(
PublisherInterface $publisher
) {
$this->publisher = $publisher;
}
/**
* Adding data to queue
*
* @param $data
* @return void
*/
public function publishData($data)
{
$this->publisher->publish(self::TOPIC_NAME, $data);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace JR\NetSuite\Model\ResourceModel;
use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class CustomerQueue extends AbstractDb {
/**
* Initialize resource
*
* @return void
*/
public function _construct()
{
$this->_init('jr_netsuite_customer_queue', 'id');
}
}
@@ -0,0 +1,101 @@
<?php
namespace JR\NetSuite\Model\ResourceModel\CustomerQueue;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use JR\NetSuite\Model\CustomerQueue;
use JR\NetSuite\Model\ResourceModel\CustomerQueue as CustomerQueueResource;
class Collection extends AbstractCollection
{
protected function _construct()
{
$this->_init(CustomerQueue::class, CustomerQueueResource::class);
}
/**
* Get next items in the queue based on batch size
*
* @param int $type_id
* @param int $batchSize
* @return \Magento\Framework\Data\Collection\AbstractDb
*/
public function getNext($batchSize = null)
{
$collection = $this
->addFieldToSelect('*')
->addFieldToFilter('status', ['eq' => 'pending'])
->setOrder('id', 'asc');
if ($batchSize) {
$collection->getSelect()->limit($batchSize);
}
return $collection;
}
/**
* Insert or update based on UNIQUE combo 'key-processing'
* @param $key
* @param $value
*/
public function insertOrUpdate($item)
{
$connection = $this->getConnection();
try {
// Start a transaction
// $connection->beginTransaction();
// echo json_encode($item, JSON_PRETTY_PRINT) . "\n";
// update the existing item with same netsuite_customer_id
$select = $connection->select()
->from($this->getMainTable())
->where('status = ?', 'pending')
->where('netsuite_customer_id = ?', $item['netsuite_customer_id']);
$existingItem = $connection->fetchRow($select);
if (!$existingItem) {
$existingItem = [];
} else {
$existingItem['data'] = json_decode($existingItem['data'], true);
}
$data = [
'netsuite_customer_id' => $item['netsuite_customer_id'],
'netsuite_entity_id' => $item['netsuite_entity_id'],
'data' => json_encode($item),
'messages' => '',
// 'created_at' => (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT),
'status' => 'pending',
];
// echo json_encode($data, JSON_PRETTY_PRINT) . "\n";
// update the existing item with default shipping or billing
if (isset($existingItem['id'])) {
$data['id'] = $existingItem['id'];
$item['isdefaultshipping'] = $item['isdefaultshipping'] || ($existingItem['data']['isdefaultshipping'] ?? false);
$item['isdefaultbilling'] = $item['isdefaultbilling'] || ($existingItem['data']['isdefaultbilling'] ?? false);
$item['shipping_address'] = $item['shipping_address'] ?? $existingItem['data']['shipping_address'] ?? [];
$item['billing_address'] = $item['billing_address'] ?? $existingItem['data']['billing_address'] ?? [];
$data['data'] = json_encode($item);
}
// Insert new item or update existing one
$connection->insertOnDuplicate($this->getMainTable(), $data, ['data', 'status', 'messages']);
// Commit the transaction
// $connection->commit();
} catch (\Exception $e) {
// Rollback the transaction in case of an error
$connection->rollBack();
throw new \Magento\Framework\Exception\LocalizedException(
__('Error in insertOrUpdate: %1', $e->getMessage()),
$e
);
}
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace JR\NetSuite\Model\ResourceModel;
use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Location extends AbstractDb {
/**
* Initialize resource
*
* @return void
*/
public function _construct()
{
$this->_init('jr_netsuite_location', 'location_id');
}
/**
* Insert or update based on UNIQUE combo 'key-processing'
*
* @param $key
* @param $value
* @param $type_id
*/
public function insertOrUpdate($item)
{
$connection = $this->getConnection();
// get the existing item with same netsuite_id
$location = $connection->fetchRow(
$connection->select()
->from($this->getMainTable())
->where('netsuite_id = ?', $item['netsuite_id'])
);
if (!$location) {
$location = [];
}
// $this->getConnection()->delete($this->getMainTable(), ['`netsuite_id` = ?' => $item['netsuite_id']]);
if (isset($location['location_id'])) {
$item['location_id'] = $location['location_id'];
}
if (strpos($item['address'], "\r\n") !== false) {
$address = explode("\r\n", $item['address']);
// if (trim($address[0]) == 'LTS Associate Inc.') {
// array_shift($address);
// }
// if (trim($address[count($address) - 1]) == 'United States') {
// array_pop($address);
// }
$item['address'] = implode(" ", $address);
}
$connection->insertOnDuplicate($this->getMainTable(), $item, ['netsuite_id', 'name', 'address']);
}
/**
* save Locations
* @param $locations
*/
public function saveLocations($locations)
{
foreach ($locations as $location) {
$this->insertOrUpdate($location);
}
}
}
@@ -0,0 +1,42 @@
<?php
namespace JR\NetSuite\Model\ResourceModel\Location;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use JR\NetSuite\Model\Location;
use JR\NetSuite\Model\ResourceModel\Location as LocationResource;
class Collection extends AbstractCollection
{
protected function _construct()
{
$this->_init(Location::class, LocationResource::class);
}
/**
* Insert or update based on UNIQUE combo 'key-processing'
* @param $key
* @param $value
*/
public function insertOrUpdate($item)
{
$connection = $this->getConnection();
try {
// Start a transaction
// $connection->beginTransaction();
// Insert new item or update existing one
$connection->insertOnDuplicate($this->getMainTable(), $item, ['data', 'status']);
// Commit the transaction
// $connection->commit();
} catch (\Exception $e) {
// Rollback the transaction in case of an error
$connection->rollBack();
throw new \Magento\Framework\Exception\LocalizedException(
__('Error in insertOrUpdate: %1', $e->getMessage()),
$e
);
}
}
}
@@ -0,0 +1,23 @@
<?php
namespace JR\NetSuite\Model\ResourceModel\NetSuite;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'entity_id';
protected $_eventPrefix = 'jrnetsuite_product_queue_collection';
protected $_eventObject = 'jrnetsuite_product_collection';
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(
\JR\NetSuite\Model\Data\ProductQueueItem::class,
\JR\NetSuite\Model\ResourceModel\ProductQueue::class
);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace JR\NetSuite\Model\ResourceModel;
use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class OrderQueue extends AbstractDb {
/**
* Initialize resource
*
* @return void
*/
public function _construct()
{
$this->_init('jr_netsuite_order_queue', 'id');
}
}
@@ -0,0 +1,112 @@
<?php
namespace JR\NetSuite\Model\ResourceModel\OrderQueue;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use JR\NetSuite\Model\OrderQueue;
use JR\NetSuite\Model\ResourceModel\OrderQueue as OrderQueueResource;
use JR\NetSuite\Helper\Data as Helper;
class Collection extends AbstractCollection {
protected function _construct() {
$this->_init(OrderQueue::class, OrderQueueResource::class);
}
/**
* Get next items in the queue based on batch size
*
* @param int $type_id
* @param int $batchSize
* @return \Magento\Framework\Data\Collection\AbstractDb
*/
public function getNext($batchSize = null) {
$collection = $this->addFieldToSelect('*')
->addFieldToFilter('status', ['eq' => 'pending'])
->setOrder('id', 'asc');
if ($batchSize) {
$collection->getSelect()->limit($batchSize);
}
return $collection;
}
/**
* Insert or update based on UNIQUE combo 'key-processing'
* @param $key
* @param $value
*/
public function insertOrUpdate($item) {
$connection = $this->getConnection();
try {
// Start a transaction
// $connection->beginTransaction();
// echo json_encode($item, JSON_PRETTY_PRINT) . "\n";
// update the existing item with same netsuite_order_id
$select = $connection->select()
->from($this->getMainTable())
->where('netsuite_order_id = ?', $item['netsuite_order_id']);
$existingItem = $connection->fetchRow($select);
if (!$existingItem) {
$existingItem = [];
}
// if the existing item is already success and the data is the same, skip
if (isset($existingItem['status']) && $existingItem['status'] == 'success'
&& isset($existingItem['data']) && $existingItem['data'] == json_encode($item)) {
return;
}
$recorded_at = \DateTime::createFromFormat('m/d/Y g:i a', $item['last_modified_date'], new \DateTimeZone('America/Los_Angeles'));
$recorded_at->setTimezone(new \DateTimeZone('UTC'));
$data = [
'netsuite_order_id' => $item['netsuite_order_id'],
'data' => json_encode($item),
'messages' => '',
'recorded_at' => $recorded_at->format('Y-m-d H:i:s'),
// 'created_at' => (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT),
'status' => 'pending',
];
// update the existing item with same netsuite_order_id
if (isset($existingItem['id'])) {
$data['id'] = $existingItem['id'];
}
// Insert new item or update existing one
$connection->insertOnDuplicate($this->getMainTable(), $data, ['data', 'status', 'messages', 'recorded_at']);
// Commit the transaction
// $connection->commit();
} catch (\Exception $e) {
// Rollback the transaction in case of an error
$connection->rollBack();
throw new \Magento\Framework\Exception\LocalizedException(
__('Error in insertOrUpdate: %1', $e->getMessage()),
$e
);
}
}
/**
* Get last sync netsuite order id
*
* @return string
*/
public function getLastSyncRecordDate() {
$select = $this->getConnection()->select()
->from($this->getMainTable(), ['recorded_at'])
->order('recorded_at DESC')
->limit(1);
return $this->getConnection()->fetchOne($select);
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace JR\NetSuite\Model\ResourceModel;
use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class ProductQueue extends AbstractDb
{
/**
* Initialize resource
*
* @return void
*/
public function _construct()
{
$this->_init('jr_netsuite_product_queue', 'id');
}
/**
* Insert or update based on UNIQUE combo 'key-processing'
*
* @param $key
* @param $value
* @param $type_id
*/
public function insertOrUpdate($item)
{
$connection = $this->getConnection();
// get the existing item with same netsuite_product_id
$productQueue = $connection->fetchRow(
$connection->select()
->from($this->getMainTable())
->where('netsuite_product_id = ?', $item['netsuite_product_id'])
->where('data like ?', '%"locationId":"' . ($item['locationId'] ?? "") . '"%')
);
if (!$productQueue) {
$productQueue = [];
}
// if the existing item is already success and the data is the same, skip
if (isset($productQueue['status']) && $productQueue['status'] == 'success'
&& isset($productQueue['data']) && $productQueue['data'] == json_encode($item)) {
return;
}
// $this->getConnection()->delete($this->getMainTable(), ['`netsuite_product_id` = ?' => $item['netsuite_product_id']]);
$data = [
'netsuite_product_id' => $item['netsuite_product_id'],
'sku' => $item['sku'],
'data' => json_encode($item),
// 'created_at' => (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT),
'status' => 'pending',
];
// update the existing item with same netsuite_product_id
if (isset($productQueue['id'])) {
$data['id'] = $productQueue['id'];
}
$connection->insertOnDuplicate($this->getMainTable(), $data, ['data', 'status']);
}
/**
* Set the item in the queue as processing
* @param $id
* @param string $value
* @return bool
*/
public function setProcessing($id, $value = 1)
{
if (!$id) {
return false;
}
$this->getConnection()->update(
$this->getMainTable(),
['status' => $value],
['id = ?' => (int) $id]
);
return true;
}
public function getProcessing($id)
{
$select = $this->getConnection()->select()->from(
$this->getMainTable(),
'status'
)->where(
'id = :id'
);
return $this->getConnection()->fetchOne($select, [':id' => $id]);
}
}
@@ -0,0 +1,119 @@
<?php
namespace JR\NetSuite\Model\ResourceModel\ProductQueue;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use JR\NetSuite\Model\Data\ProductQueueItem;
use JR\NetSuite\Model\ResourceModel\ProductQueue as ProductQueueResource;
class Collection extends AbstractCollection
{
protected function _construct()
{
$this->_init(ProductQueueItem::class, ProductQueueResource::class);
}
/**
* Get next items in the queue based on batch size
*
* @param int $type_id
* @param int $batchSize
* @return \Magento\Framework\Data\Collection\AbstractDb
*/
public function getNext($batchSize = null)
{
$collection = $this
->addFieldToSelect('*')
->addFieldToFilter('status', ['eq' => 'pending'])
->setOrder('id', 'asc');
if ($batchSize) {
$collection->getSelect()->limit($batchSize);
}
return $collection;
}
// Custom methods to add more specialized filters
public function addStatusFilter($status)
{
$this->addFieldToFilter('status', $status);
return $this;
}
public function addDateRangeFilter($fromDate, $toDate)
{
$this->addFieldToFilter('updated_at', ['from' => $fromDate, 'to' => $toDate]);
return $this;
}
public function addUnprocessedFilter()
{
$this->addFieldToFilter('status', ['neq' => 'processed']);
return $this;
}
public function addPendingFilter()
{
$this->addFieldToFilter('status', ['eq' => 'pending']);
return $this;
}
public function addProcessingFilter()
{
$this->addFieldToFilter('status', ['eq' => 'processing']);
return $this;
}
public function addFailedFilter()
{
$this->addFieldToFilter('status', ['eq' => 'failed']);
return $this;
}
public function addProcessedFilter()
{
$this->addFieldToFilter('status', ['eq' => 'processed']);
return $this;
}
public function addUpdatedAtFilter($fromDate, $toDate)
{
$this->addFieldToFilter('updated_at', ['from' => $fromDate, 'to' => $toDate]);
return $this;
}
public function addCreatedAtFilter($fromDate, $toDate)
{
$this->addFieldToFilter('created_at', ['from' => $fromDate, 'to' => $toDate]);
return $this;
}
public function addNetsuiteProductIdFilter($netsuiteProductId)
{
$this->addFieldToFilter('netsuite_product_id', $netsuiteProductId);
return $this;
}
public function addSkuFilter($sku)
{
$this->addFieldToFilter('sku', $sku);
return $this;
}
public function addTypeFilter($type)
{
$this->addFieldToFilter('type', $type);
return $this;
}
/**
* get all product queue items that are pending
*
* @return Collection
*/
public function getPendingItems()
{
return $this->addPendingFilter();
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace JR\NetSuite\Model\ResourceModel;
use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class RmaQueue extends AbstractDb {
/**
* Initialize resource
*
* @return void
*/
public function _construct()
{
$this->_init('jr_netsuite_rma_queue', 'id');
}
}
@@ -0,0 +1,147 @@
<?php
namespace JR\NetSuite\Model\ResourceModel\RmaQueue;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'id';
protected $_eventPrefix = 'jr_netsuite_rma_queue_collection';
protected $_eventObject = 'rma_queue_collection';
/**
* Define the resource model & the model.
*
* @return void
*/
protected function _construct()
{
$this->_init('JR\NetSuite\Model\RmaQueue', 'JR\NetSuite\Model\ResourceModel\RmaQueue');
}
/**
* get collection of RmaQueue with netsuite_tran_id filter
*
*/
public function getCollectionByNetsuiteTranId($netsuiteTranId){
$collection = $this
->addFieldToSelect('*')
->addFieldToFilter('netsuite_tran_id', ['eq' => $netsuiteTranId])
->setOrder('id', 'desc');
return $collection;
}
/**
* Get next items in the queue based on batch size
*
* @param int $batchSize
*/
public function getNext($batchSize = null)
{
$collection = $this
->addFieldToSelect('*')
->addFieldToFilter('status', ['eq' => 'pending'])
->addFieldToFilter('data', ['notnull' => true])
->setOrder('id', 'asc');
if ($batchSize) {
$collection->getSelect()->limit($batchSize);
}
return $collection;
}
/**
* Insert or update based on UNIQUE combo 'key-processing'
* @param $key
* @param $value
*/
public function insertOrUpdate($item)
{
$connection = $this->getConnection();
try {
// Start a transaction
// $connection->beginTransaction();
// echo json_encode($item, JSON_PRETTY_PRINT) . "\n";
// update the existing item with same netsuite_order_id
$select = $connection->select()
->from($this->getMainTable())
// ->where('status = ?', 'pending')
// ->where('netsuite_tran_id = ?', $item['netsuite_tran_id'])
->where('netsuite_id = ?', $item['netsuite_id']);
$existingItem = $connection->fetchRow($select);
if (!$existingItem) {
$existingItem = [];
}
// if the existing item is already success and the data is the same, skip
if (isset($existingItem['status']) && $existingItem['status'] == 'success'
&& isset($existingItem['data']) && $existingItem['data'] == json_encode($item)) {
return;
}
$recorded_at = \DateTime::createFromFormat('m/d/Y g:i a', $item['recorded_at'], new \DateTimeZone('America/Los_Angeles'));
$recorded_at->setTimezone(new \DateTimeZone('UTC'));
$data = [
'netsuite_id' => $item['netsuite_id'],
'netsuite_tran_id' => $item['netsuite_tran_id'],
'data' => json_encode($item),
'messages' => '',
'recorded_at' => $recorded_at->format('Y-m-d H:i:s'),
// 'created_at' => (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT),
'status' => 'pending',
];
// update the existing item with same netsuite_order_id
if (isset($existingItem['id'])) {
$data['id'] = $existingItem['id'];
}
// Insert new item or update existing one
$connection->insertOnDuplicate($this->getMainTable(), $data);
// Commit the transaction
// $connection->commit();
} catch (\Exception $e) {
// Rollback the transaction in case of an error
$connection->rollBack();
throw new \Magento\Framework\Exception\LocalizedException(
__('Error in insertOrUpdate: %1', $e->getMessage()),
$e
);
}
}
/**
* Get last sync netsuite rma id
*
* @return string
*/
public function getLastSyncRecordDate()
{
$select = $this->getConnection()->select()
->from($this->getMainTable(), ['recorded_at'])
->order('recorded_at DESC')
->limit(1);
return $this->getConnection()->fetchOne($select);
}
/**
* Get last sync netsuite rma id
*
* @return string
*/
public function getLastSyncNetsuiteId()
{
$select = $this->getConnection()->select()
->from($this->getMainTable(), ['netsuite_id'])
->where('data IS NOT NULL')
->order('netsuite_id DESC')
->limit(1);
return $this->getConnection()->fetchOne($select);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace JR\NetSuite\Model;
use Magento\Framework\Model\AbstractModel;
class RmaQueue extends AbstractModel
{
public function _construct()
{
$this->_init(\JR\NetSuite\Model\ResourceModel\RmaQueue::class);
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
namespace JR\NetSuite\Observer;
use Magento\Framework\Event\ObserverInterface;
use JR\NetSuite\Helper\Data;
use JR\NetSuite\Logger\Logger;
use JR\NetSuite\Model\Queue\OrderToQueue;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\MessageQueue\Model\Publisher;
use \Magento\Framework\MessageQueue\ConsumerInterface;
class OrderPlaceAfter implements ObserverInterface
{
/**
* @var Data
*/
protected $helper;
/**
* @var Logger
*/
protected $logger;
/**
* @var Json
*/
protected $json;
/**
* @var OrderToQueue
*/
protected $publisher;
public function __construct(
Data $helper,
Logger $logger,
Json $json,
OrderToQueue $publisher,
)
{
$this->helper = $helper;
$this->logger = $logger;
$this->json = $json;
$this->publisher = $publisher;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
if (!$this->helper->getNetSuiteIsEnabled()) {
return $this;
}
$order = $observer->getEvent()->getOrder();
$customerEmail = $order->getCustomerEmail();
$orderId = $order->getRealOrderId();
$this->logger->info('OrderPlace observer executed');
$this->logger->info('Order ID: ' . $order->getRealOrderId());
$orderStatus = $order->getState();
if ($orderStatus == 'pending') {
$this->logger->info('OrderPlace observer: Order status is pending');
return $this;
}
$collectedData = [
'order_id' => $orderId,
'customer_email' => $customerEmail,
'order_status' => $orderStatus
];
$this->publish($this->json->serialize($collectedData));
$msg = "\n".date('YmdHis')." increment id ".$order->getIncrementId(). " | entity_id ".$order->getId() ." | paymentMethodCode ".$order->getPayment()->getMethod();
return $this;
}
/**
* Publishing data
*
* @param $data
* @return void
*/
public function publish($data)
{
$this->publisher->publishData($data);
}
}
+96
View File
@@ -0,0 +1,96 @@
<?php
namespace JR\NetSuite\Observer;
use JR\NetSuite\Logger\Logger;
use JR\NetSuite\Model\ResourceModel\RmaQueue\CollectionFactory;
use JR\NetSuite\Model\RmaQueueFactory;
class UpdateRmaAfter implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var Logger
*/
protected $logger;
/**
* @var CollectionFactory
*/
protected $rmaQueueCollectionFactory;
/**
* @var RmaQueueFactory
*/
protected $rmaQueueFactory;
/**
* @var \Mirasvit\Rma\Api\Repository\StatusRepositoryInterface
*/
protected $statusRepository;
/**
* @var \Mirasvit\Rma\Api\Service\Rma\RmaManagementInterface
*/
private $rmaManagement;
public function __construct(
Logger $logger,
CollectionFactory $rmaQueueCollectionFactory,
RmaQueueFactory $rmaQueueFactory,
\Mirasvit\Rma\Api\Repository\StatusRepositoryInterface $statusRepository,
\Mirasvit\Rma\Api\Service\Rma\RmaManagementInterface $rmaManagement
) {
$this->logger = $logger;
$this->rmaQueueCollectionFactory = $rmaQueueCollectionFactory;
$this->rmaQueueFactory = $rmaQueueFactory;
$this->statusRepository = $statusRepository;
$this->rmaManagement = $rmaManagement;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
try {
$rma = $observer->getData('rma');
$rmaId = $rma->getId();
if (!$rmaId) {
return;
}
// if RMA status is not pending approval, do nothing
if ($this->statusRepository->get($rma->getStatusId())?->getName() !== 'Pending Approval') {
return;
}
// find RMA in queue by RMA ID
$rmaQueueCollection = $this->rmaQueueCollectionFactory->create();
$rmaQueueCollection->addFieldToFilter('rma_id', $rma->getId());
$rmaQueue = $rmaQueueCollection->getFirstItem();
// if RMA is already queued, do nothing
if ($rmaQueue?->getId()) {
return;
}
$rmaQueueCollection = $this->rmaQueueCollectionFactory->create();
$rmaQueueCollection->addFieldToFilter('status', 'processing');
$order = $this->rmaManagement->getOrder($rma);
foreach($rmaQueueCollection as $rmaQueue) {
if ($rmaQueue->getOrderIncrementId() == $order->getRealorderId()) {
return;
}
}
// if RMA is not queued, queue RMA
$rmaQueue = $this->rmaQueueFactory->create();
$data = [
'rma_id' => $rma->getId(),
'status' => 'pending',
];
$rmaQueue->setData($data);
$rmaQueue->save();
} catch (\Exception $e) {
$this->logger->error('Update RMA Queue Error: ' . $e->getMessage());
}
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace JR\NetSuite\Plugin;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class EmailNotification
{
/**
* @var ScopeConfigInterface
*/
protected $_scopeConfig;
public function __construct(
ScopeConfigInterface $scopeConfig
) {
$this->_scopeConfig = $scopeConfig;
}
public function aroundNewAccount(
\Magento\Customer\Model\EmailNotification $subject,
\Closure $proceed,
$customer,
$type = \Magento\Customer\Model\EmailNotification::NEW_ACCOUNT_EMAIL_REGISTERED,
$backUrl = '',
$storeId = null,
$sendemailStoreId = null
) {
$disabled = $customer->getCustomAttribute('netsuite_id');
if ($disabled) {
return;
}
$result = $proceed($customer, $type, $backUrl, $storeId, $sendemailStoreId);
return $result;
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace JR\NetSuite\Plugin;
class SendEmailWhenRmaChanged
{
/**
* @var \JR\NetSuite\Model\ResourceModel\RmaQueue\CollectionFactory
*/
private $rmaQueueCollectionFactory;
/**
* @var \Mirasvit\Rma\Api\Service\Rma\RmaManagementInterface
*/
private $rmaManagement;
public function __construct(
\JR\NetSuite\Model\ResourceModel\RmaQueue\CollectionFactory $rmaQueueCollectionFactory,
\Mirasvit\Rma\Api\Service\Rma\RmaManagementInterface $rmaManagement
)
{
$this->rmaQueueCollectionFactory = $rmaQueueCollectionFactory;
$this->rmaManagement = $rmaManagement;
}
public function aroundOnRmaStatusChange(
\Mirasvit\Rma\Helper\Rma\Event $subject,
callable $proceed,
$rma
) {
// if RMA just created, do nothing
$rmaQueueCollection = $this->rmaQueueCollectionFactory->create();
$rmaQueueCollection->addFieldToFilter('status', 'processing');
$order = $this->rmaManagement->getOrder($rma);
foreach ($rmaQueueCollection as $rmaQueue) {
if ($rmaQueue->getOrderIncrementId() == $order->getRealorderId()) {
return;
}
}
$result = $proceed($rma);
return $result;
}
}

Some files were not shown because too many files have changed in this diff Show More