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
+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);
}
}