ltsecurityinc安防产品在线商城代码
This commit is contained in:
+382
@@ -0,0 +1,382 @@
|
||||
<?php
|
||||
|
||||
namespace JR\NetSuite\Service;
|
||||
|
||||
class AttributesSyncService
|
||||
{
|
||||
|
||||
protected $productAttributeRepositoryInterface;
|
||||
protected $productAttributeInterfaceFactory;
|
||||
protected $tableFactory;
|
||||
protected $attributeOptionManagement;
|
||||
protected $optionLabelFactory;
|
||||
protected $attributeOptionInterfaceFactory;
|
||||
protected $productResource;
|
||||
protected $optionsFactory;
|
||||
protected $attributeFactory;
|
||||
protected $attributeGroupInterfaceFactory;
|
||||
protected $attributeGroupInterface;
|
||||
protected $entityType;
|
||||
protected $entityTypeCode;
|
||||
protected $entityTypeId;
|
||||
protected $attributeSetId;
|
||||
|
||||
protected $helper;
|
||||
protected $sqquidGroup;
|
||||
protected $groupCode;
|
||||
protected $cacheAttributeData;
|
||||
protected $cacheAttributeValueData;
|
||||
protected $productAttributeData;
|
||||
|
||||
protected $groupName;
|
||||
|
||||
public function __construct(
|
||||
\JR\NetSuite\Helper\Data $helper,
|
||||
\Magento\Eav\Model\Entity\Attribute\Source\TableFactory $tableFactory,
|
||||
\Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
|
||||
\Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory $optionLabelFactory,
|
||||
\Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $attributeOptionInterfaceFactory,
|
||||
\Magento\Catalog\Api\ProductAttributeRepositoryInterface $productAttributeRepositoryInterface,
|
||||
\Magento\Catalog\Api\Data\ProductAttributeInterfaceFactory $productAttributeInterfaceFactory,
|
||||
\Magento\Catalog\Model\ResourceModel\Product $productResource,
|
||||
\Magento\ConfigurableProduct\Helper\Product\Options\Factory $optionsFactory,
|
||||
\Magento\Catalog\Model\ProductFactory $productFactory,
|
||||
\Magento\Eav\Api\Data\AttributeGroupInterfaceFactory $attributeGroupInterfaceFactory,
|
||||
\Magento\Eav\Api\Data\AttributeGroupInterface $attributeGroupInterface,
|
||||
\Magento\Eav\Model\Entity\AttributeFactory $attributeFactory
|
||||
) {
|
||||
|
||||
$this->attributeGroupInterfaceFactory = $attributeGroupInterfaceFactory;
|
||||
$this->attributeGroupInterface = $attributeGroupInterface;
|
||||
$this->attributeFactory = $attributeFactory;
|
||||
|
||||
$this->helper = $helper;
|
||||
|
||||
$this->productResource = $productResource;
|
||||
$this->productAttributeRepositoryInterface = $productAttributeRepositoryInterface;
|
||||
$this->productAttributeInterfaceFactory = $productAttributeInterfaceFactory;
|
||||
$this->tableFactory = $tableFactory;
|
||||
$this->attributeOptionManagement = $attributeOptionManagement;
|
||||
$this->optionLabelFactory = $optionLabelFactory;
|
||||
$this->attributeOptionInterfaceFactory = $attributeOptionInterfaceFactory;
|
||||
$this->optionsFactory = $optionsFactory;
|
||||
|
||||
$this->cacheAttributeData = [];
|
||||
$this->cacheAttributeValueData = [];
|
||||
|
||||
// /*
|
||||
// * We need to check if our group is on the default attribute set.. if not we should create
|
||||
// */
|
||||
// $this->groupName = "Sqquid";
|
||||
// $this->groupCode = $this->helper->convertStringToCode($this->groupName);
|
||||
// // maybe use something like \Magento\Catalog\Model\Product::ENTITY
|
||||
// $this->entityTypeId = 4;
|
||||
// $this->attributeSetId = $productFactory->create()->getDefaultAttributeSetId();
|
||||
|
||||
// $this->sqquidGroup = $this->attributeGroupInterface->load($this->groupName, 'attribute_group_name');
|
||||
|
||||
// if (!$this->sqquidGroup->itemExists()) {
|
||||
// $group = $this->attributeGroupInterfaceFactory->create();
|
||||
// $group->setAttributeSetId($this->attributeSetId)
|
||||
// ->setAttributeGroupName($this->groupName)
|
||||
// ->setSortOrder(100)
|
||||
// ->setAttributeGroupCode($this->groupCode);
|
||||
|
||||
// $group->save();
|
||||
|
||||
// $this->sqquidGroup = $group;
|
||||
// }
|
||||
|
||||
// $this->setIncludeAttribute();
|
||||
}
|
||||
|
||||
// private function setIncludeAttribute()
|
||||
// {
|
||||
// $this->findOrCreateAttribute('Include', 'boolean', 'Magento\Eav\Model\Entity\Attribute\Source\Boolean');
|
||||
// }
|
||||
|
||||
/**
|
||||
* @param \Magento\Catalog\Model\Product $product
|
||||
* @param array $data
|
||||
* @return array|bool
|
||||
*/
|
||||
public function processAttributes(\Magento\Catalog\Model\Product $product, $data)
|
||||
{
|
||||
|
||||
// if ($product->getSqquidInclude() != true) {
|
||||
// $product->setData('sqquid_include', true);
|
||||
// $this->productResource->saveAttribute($product, 'sqquid_include');
|
||||
// }
|
||||
|
||||
if (!isset($data['Attributes'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$productAttributeData = [];
|
||||
|
||||
foreach ($data['Attributes'] as $attribute) {
|
||||
if ($attribute['value'] === null || $attribute['value'] === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$type = null;
|
||||
|
||||
if (isset($attribute['type'])) {
|
||||
$type = $attribute['type'];
|
||||
}
|
||||
|
||||
if ($result = $this->setAttributeData($product, $attribute['label'], $attribute['value'], $type)) {
|
||||
$productAttributeData[] = $result;
|
||||
}
|
||||
}
|
||||
|
||||
return $productAttributeData;
|
||||
}
|
||||
|
||||
private function setAttributeData(\Magento\Catalog\Model\Product $product, $label, $value, $type = 'select')
|
||||
{
|
||||
$createType = $type == 'configurable_select' ? 'select' : $type;
|
||||
$attribute = $this->findOrCreateAttribute($label, $createType);
|
||||
|
||||
if ($type == 'text') {
|
||||
if ($product->getData($attribute->getAttributeCode()) != $value) {
|
||||
$product->setData($attribute->getAttributeCode(), $value);
|
||||
$this->productResource->saveAttribute($product, $attribute->getAttributeCode());
|
||||
}
|
||||
}
|
||||
|
||||
if ($type == 'select' || $type == 'configurable_select') {
|
||||
$valueId = $this->findOrCreateValue($attribute, $value);
|
||||
|
||||
if ($product->getAttributeText($attribute->getAttributeCode()) != $value) {
|
||||
$product->setData($attribute->getAttributeCode(), $valueId);
|
||||
$this->productResource->saveAttribute($product, $attribute->getAttributeCode());
|
||||
}
|
||||
|
||||
if ($type == 'configurable_select') {
|
||||
$configurationData = [
|
||||
'label' => $attribute->getStoreLabel(),
|
||||
'attribute_id' => $attribute->getId(),
|
||||
'attribute_code' => $attribute->getAttributeCode(),
|
||||
'value_index' => $valueId,
|
||||
'value_label' => $value,
|
||||
'pricing_value' => $product->getPrice()
|
||||
];
|
||||
|
||||
return $configurationData;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function findOrCreateValue($attribute, $value)
|
||||
{
|
||||
if (!isset($this->cacheAttributeValueData[$attribute->getId()])) {
|
||||
$this->cacheAttributeValueData[$attribute->getId()] = []; // just to set it up
|
||||
}
|
||||
|
||||
if (isset($this->cacheAttributeValueData[$attribute->getId()][$value])) {
|
||||
return $this->cacheAttributeValueData[$attribute->getId()][$value];
|
||||
}
|
||||
|
||||
$valueId = $this->findOrCreateValueFromDatabase($attribute, $value);
|
||||
|
||||
$this->cacheAttributeValueData[$attribute->getId()][$value] = $valueId;
|
||||
|
||||
return $valueId;
|
||||
}
|
||||
|
||||
public function findOrCreateValueFromDatabase($attribute, $label)
|
||||
{
|
||||
if (strlen($label) < 1) {
|
||||
throw new \Magento\Framework\Exception\LocalizedException(
|
||||
__('Label for %1 must not be empty.', $attribute->getId())
|
||||
);
|
||||
}
|
||||
|
||||
if ($optionId = $this->getOptionId($attribute, $label)) {
|
||||
return $optionId;
|
||||
}
|
||||
|
||||
/** @var \Magento\Eav\Model\Entity\Attribute\OptionLabel $optionLabel */
|
||||
$optionLabel = $this->optionLabelFactory->create();
|
||||
$optionLabel->setStoreId(0);
|
||||
$optionLabel->setLabel($label);
|
||||
|
||||
$option = $this->attributeOptionInterfaceFactory->create();
|
||||
$option->setLabel($optionLabel);
|
||||
$option->setStoreLabels([$optionLabel]);
|
||||
$option->setSortOrder(0);
|
||||
$option->setIsDefault(false);
|
||||
|
||||
$this->attributeOptionManagement->add(
|
||||
\Magento\Catalog\Model\Product::ENTITY,
|
||||
$attribute->getId(),
|
||||
$option
|
||||
);
|
||||
|
||||
// Get the inserted ID. Should be returned from the installer, but it isn't.
|
||||
$optionId = $this->getOptionId($attribute, $label);
|
||||
|
||||
return $optionId;
|
||||
}
|
||||
|
||||
public function getOptionId($attribute, $label)
|
||||
{
|
||||
|
||||
// We have to generate a new sourceModel instance each time through to prevent it from
|
||||
// referencing its _options cache. No other way to get it to pick up newly-added values.
|
||||
|
||||
/** @var \Magento\Eav\Model\Entity\Attribute\Source\Table $sourceModel */
|
||||
$sourceModel = $this->tableFactory->create();
|
||||
$sourceModel->setAttribute($attribute);
|
||||
|
||||
foreach ($sourceModel->getAllOptions() as $option) {
|
||||
$this->cacheAttributeValueData[$attribute->getAttributeId()][$option['label']] = $option['value'];
|
||||
}
|
||||
|
||||
// Return option ID if exists
|
||||
if (isset($this->cacheAttributeValueData[$attribute->getAttributeId()][$label])) {
|
||||
return $this->cacheAttributeValueData[$attribute->getAttributeId()][$label];
|
||||
}
|
||||
|
||||
// Return false if does not exist
|
||||
return false;
|
||||
}
|
||||
|
||||
private function findOrCreateAttribute($label, $type, $source = null)
|
||||
{
|
||||
$code = $label . '-' . $type;
|
||||
if (isset($this->cacheAttributeData[$code])) {
|
||||
return $this->cacheAttributeData[$code];
|
||||
}
|
||||
|
||||
$attribute = $this->findOrCreateAttributeFromDatabase($label, $type, $source);
|
||||
$this->cacheAttributeData[$code] = $attribute;
|
||||
return $attribute;
|
||||
}
|
||||
|
||||
public function findOrCreateAttributeFromDatabase($label, $attribute_type, $source = null)
|
||||
{
|
||||
|
||||
$code = $this->helper->convertStringToCode($label);
|
||||
|
||||
$attribute_code = 'netsuite_' . $code;
|
||||
|
||||
$mustCreateAttribute = false;
|
||||
|
||||
try {
|
||||
$attribute = $this->productAttributeRepositoryInterface->get($attribute_code);
|
||||
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
|
||||
// Yes, if there is a NoSuchEntityException, it means that the attributes does not exist
|
||||
$mustCreateAttribute = true;
|
||||
}
|
||||
|
||||
if (!$mustCreateAttribute) {
|
||||
return $attribute;
|
||||
}
|
||||
|
||||
$attribute = $this->productAttributeInterfaceFactory->create();
|
||||
$attribute->setEntityTypeId($this->entityTypeId);
|
||||
|
||||
$data = [
|
||||
'group' => $this->groupName,
|
||||
'attribute_code' => $attribute_code,
|
||||
'frontend_label' => $label,
|
||||
'backend_type' => '',
|
||||
'frontend_input' => $attribute_type,
|
||||
'is_required' => false,
|
||||
'is_unique' => false,
|
||||
'is_user_defined' => true,
|
||||
'sort_order' => 100,
|
||||
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
|
||||
'used_in_product_listing' => false,
|
||||
'searchable' => true,
|
||||
'comparable' => true,
|
||||
'visible_on_front' => true,
|
||||
'visible' => true
|
||||
];
|
||||
|
||||
if ($source) {
|
||||
$data['source'] = $source;
|
||||
}
|
||||
|
||||
$attribute->setData($data);
|
||||
|
||||
$this->productAttributeRepositoryInterface->save($attribute);
|
||||
|
||||
$attributeEntity = $this->attributeFactory->create();
|
||||
$attributeEntity->setAttributeSetId($this->attributeSetId)
|
||||
->setEntityTypeId($this->entityTypeId)
|
||||
->setAttributeGroupId($this->sqquidGroup->getId())
|
||||
->setAttributeId($attribute->getId())
|
||||
->setSortOrder(0);
|
||||
|
||||
$attributeEntity->save();
|
||||
|
||||
return $attribute;
|
||||
}
|
||||
|
||||
public function attachAttributesFromChildData($product, $configurableProductsData)
|
||||
{
|
||||
|
||||
if (!$configurableProductsData) {
|
||||
return $product;
|
||||
}
|
||||
$associatedProductIds = array_keys($configurableProductsData);
|
||||
|
||||
$tempValueArray = [];
|
||||
$usedValueArray = [];
|
||||
|
||||
$attributeValueData = [];
|
||||
$usedAttributeArray = [];
|
||||
|
||||
foreach ($configurableProductsData as $item) { // get unique attribute IDs
|
||||
|
||||
foreach ($item as $data) {
|
||||
if (!isset($tempValueArray[$data['attribute_id']])) {
|
||||
$tempValueArray[$data['attribute_id']] = [];
|
||||
}
|
||||
|
||||
if (in_array($data['value_index'], $usedValueArray)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tempValueArray[$data['attribute_id']][] = [
|
||||
'attribute_id' => $data['attribute_id'],
|
||||
'label' => $data['value_label'],
|
||||
'value_index' => $data['value_index'],
|
||||
];
|
||||
|
||||
$usedValueArray[] = $data['value_index'];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($configurableProductsData as $item) { // get unique attribute IDs
|
||||
foreach ($item as $data) {
|
||||
if (in_array($data['attribute_id'], $usedAttributeArray)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$attributeValueData[] = [
|
||||
'attribute_id' => $data['attribute_id'],
|
||||
'code' => $data['attribute_code'],
|
||||
'label' => $data['label'],
|
||||
'position' => '0',
|
||||
'values' => $tempValueArray[$data['attribute_id']],
|
||||
];
|
||||
|
||||
$usedAttributeArray[] = $data['attribute_id'];
|
||||
}
|
||||
}
|
||||
|
||||
$configurableOptions = $this->optionsFactory->create($attributeValueData);
|
||||
$extensionConfigurableAttributes = $product->getExtensionAttributes();
|
||||
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
|
||||
$extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds); // associated product IDs
|
||||
$product->setExtensionAttributes($extensionConfigurableAttributes);
|
||||
|
||||
return $product;
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
namespace JR\NetSuite\Service;
|
||||
|
||||
class CategoriesSyncService
|
||||
{
|
||||
|
||||
protected $helper;
|
||||
protected $categoryFactory;
|
||||
protected $categoryColFactory;
|
||||
protected $categories;
|
||||
protected $rootCategories;
|
||||
protected $defaultCategory;
|
||||
|
||||
public function __construct(
|
||||
\Psr\Log\LoggerInterface $logger,
|
||||
\JR\NetSuite\Helper\Data $helper,
|
||||
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
|
||||
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryColFactory
|
||||
) {
|
||||
$this->categories = [];
|
||||
$this->rootCategories = [];
|
||||
|
||||
$this->categoryFactory = $categoryFactory;
|
||||
$this->categoryColFactory = $categoryColFactory;
|
||||
|
||||
$this->helper = $helper;
|
||||
$this->defaultCategory = $this->helper->getDefaultCategory();
|
||||
|
||||
$this->initCategories();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
public function getOrCreateCategoryIds($data)
|
||||
{
|
||||
|
||||
if (!isset($data['categories'])) {
|
||||
return [$this->defaultCategory];
|
||||
}
|
||||
|
||||
$categoryIds = [];
|
||||
|
||||
if ($this->is_multi($data['categories'])) {
|
||||
//special case: list of categories
|
||||
foreach ($data['categories'] as $categoryArray) {
|
||||
$categoryPath = implode("/", $categoryArray);
|
||||
$categoryIds[] = $this->getOrCreateCategory($categoryPath);
|
||||
}
|
||||
} elseif (is_array($data['categories'])) {
|
||||
$categoryPath = implode("/", $data['categories']);
|
||||
$categoryIds[] = $this->getOrCreateCategory($categoryPath);
|
||||
}
|
||||
|
||||
return $categoryIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create category id based on a path. A path is the string equivalent of the tree node of the category
|
||||
* $categoryPath = 'Soccer/Shoes/Firm Ground'
|
||||
* this path the function will search if it exists we know the id
|
||||
* otherwise it will recursively try to get the parent id. Once it finds the parent id it creates a new category.
|
||||
* if the parent is the top root category, it stops recursion and starts creating new branch.
|
||||
*
|
||||
* @param $categoryPath
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getOrCreateCategory($categoryPath)
|
||||
{
|
||||
$currentCategories = $this->getCurrentCategories();
|
||||
|
||||
if (empty($categoryPath) || $categoryPath == "") {
|
||||
return $this->defaultCategory;
|
||||
}
|
||||
|
||||
if (isset($currentCategories[$categoryPath])) {
|
||||
return $currentCategories[$categoryPath];
|
||||
}
|
||||
|
||||
//create category based on the path and return the new category ID
|
||||
//get or create parent, return id
|
||||
//if category path is empty, return root id
|
||||
//once I get an id back, go ahead and create child category
|
||||
$catsArray = explode("/", $categoryPath);
|
||||
$categoryName = array_pop($catsArray);
|
||||
|
||||
$parentId = $this->getOrCreateCategory(implode("/", $catsArray));
|
||||
$parentCategory = $this->categoryFactory->create()->load($parentId);
|
||||
|
||||
$category = $this->categoryFactory->create();
|
||||
$category->setPath($parentCategory->getPath())
|
||||
->setParentId($parentId)
|
||||
->setName($categoryName)
|
||||
->setIsActive(true)
|
||||
->setIncludeInMenu(true)
|
||||
->save();
|
||||
|
||||
$this->categories[$categoryPath] = $category->getId();
|
||||
|
||||
return $category->getId();
|
||||
}
|
||||
|
||||
protected function getCurrentCategories()
|
||||
{
|
||||
if (!$this->categories) { // just in case :)
|
||||
$this->initCategories();
|
||||
}
|
||||
|
||||
return $this->categories;
|
||||
}
|
||||
|
||||
protected function is_multi($a)
|
||||
{
|
||||
$rv = array_filter($a, 'is_array');
|
||||
if (count($rv) > 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make an array of all categories by name and path. key = path, value = id
|
||||
* The main purpose of this structure is to allow for easy search of categories
|
||||
* see if they exist and if not, create one in the correct node easily
|
||||
* Exmple:
|
||||
* Array() = {
|
||||
* 'Footwear' => 2,
|
||||
* 'Footwear/Firm Ground Soccer Shoes' => 3,
|
||||
* 'Clearance' => 4,
|
||||
* 'Clearance/Soccer Shoes' => 5,
|
||||
* 'Clearance/Soccer Shoes/Firm Groun' => 6
|
||||
* }
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function initCategories()
|
||||
{
|
||||
$collection = $this->categoryColFactory->create()->addNameToResult();
|
||||
/* @var $collection \Magento\Catalog\Model\ResourceModel\Category\Collection */
|
||||
foreach ($collection as $category) {
|
||||
$structure = preg_split('#/+#', $category->getPath());
|
||||
$pathSize = count($structure);
|
||||
if ($pathSize > 1) {
|
||||
$path = [];
|
||||
for ($i = 1; $i < $pathSize; $i++) {
|
||||
$path[] = $collection->getItemById($structure[$i])->getName();
|
||||
}
|
||||
|
||||
$this->rootCategories[$category->getId()] = ['name' => array_shift($path), 'id' => $structure[0]];
|
||||
|
||||
if ($pathSize > 2) {
|
||||
$this->categories[implode('/', $path)] = $category->getId();
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace JR\NetSuite\Service;
|
||||
|
||||
use Magento\Customer\Api\CustomerRepositoryInterface;
|
||||
use Magento\Customer\Api\Data\CustomerInterface;
|
||||
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
|
||||
use Magento\Customer\Api\Data\AddressInterfaceFactory;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Exception\NoSuchEntityException;
|
||||
|
||||
class CustomersSyncService {
|
||||
|
||||
/**
|
||||
* @var \Magento\Customer\Api\CustomerRepositoryInterface
|
||||
*/
|
||||
protected $customerRepository;
|
||||
|
||||
/**
|
||||
* @var \Magento\Customer\Api\Data\CustomerInterfaceFactory
|
||||
*/
|
||||
protected $customerFactory;
|
||||
|
||||
/**
|
||||
* @var \Magento\Customer\Api\Data\AddressInterfaceFactory
|
||||
*/
|
||||
protected $addressFactory;
|
||||
|
||||
/**
|
||||
* @var \JR\NetSuite\Helper\Data
|
||||
*/
|
||||
|
||||
protected $helper;
|
||||
|
||||
/**
|
||||
* @var \JR\NetSuite\Logger\Logger
|
||||
*/
|
||||
protected $logger;
|
||||
|
||||
/**
|
||||
* CustomersSyncService constructor.
|
||||
* @param CustomerRepositoryInterface $customerRepository
|
||||
* @param CustomerInterfaceFactory $customerFactory
|
||||
* @param AddressInterfaceFactory $addressFactory
|
||||
* @param \JR\NetSuite\Helper\Data $helper
|
||||
* @param \JR\NetSuite\Logger\Logger $logger
|
||||
*/
|
||||
public function __construct(
|
||||
CustomerRepositoryInterface $customerRepository,
|
||||
CustomerInterfaceFactory $customerFactory,
|
||||
AddressInterfaceFactory $addressFactory,
|
||||
\JR\NetSuite\Helper\Data $helper,
|
||||
\JR\NetSuite\Logger\Logger $logger
|
||||
) {
|
||||
$this->customerRepository = $customerRepository;
|
||||
$this->customerFactory = $customerFactory;
|
||||
$this->addressFactory = $addressFactory;
|
||||
$this->helper = $helper;
|
||||
$this->logger = $logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or Update a customer based on the provided data
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function createOrSkip(array $data) {
|
||||
$this->logger->info("[CustomersSyncService] createOrSkip: customer data -> " . json_encode($data, JSON_PRETTY_PRINT));
|
||||
|
||||
if (!isset($data['email']) || empty($data['email'])) {
|
||||
throw new LocalizedException(__('Email is required.'));
|
||||
}
|
||||
|
||||
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
|
||||
throw new LocalizedException(__('Invalid email address.'));
|
||||
}
|
||||
|
||||
try {
|
||||
// Try to load existing customer by email
|
||||
$customer = $this->customerRepository->get($data['email']);
|
||||
|
||||
return [
|
||||
'data' => $customer,
|
||||
'is_new' => false
|
||||
];
|
||||
} catch (NoSuchEntityException $e) {
|
||||
|
||||
if (!isset($data['firstname']) || empty($data['firstname'])) {
|
||||
throw new LocalizedException(__('First name is required.'));
|
||||
}
|
||||
|
||||
if (!isset($data['lastname']) || empty($data['lastname'])) {
|
||||
throw new LocalizedException(__('Last name is required.'));
|
||||
}
|
||||
|
||||
// Customer does not exist, create a new one
|
||||
$customer = $this->customerFactory->create();
|
||||
|
||||
$customer->setWebsiteId('1')->setStoreId('1');
|
||||
|
||||
// Populate customer object with new data
|
||||
$customer->setEmail($data['email'])
|
||||
->setFirstname($data['firstname'] ?? '')
|
||||
->setLastname($data['lastname'] ?? '');
|
||||
|
||||
// set customer group
|
||||
if (!empty($data['group_id'] ?? '')) {
|
||||
$customer->setGroupId($data['group_id']);
|
||||
}
|
||||
|
||||
// set reporting office
|
||||
if (!empty($data['reporting_office'] ?? '')) {
|
||||
$customer->setNetsuiteCsegNcgRepOffice($data['reporting_office']);
|
||||
}
|
||||
|
||||
// Additional data can be set as needed
|
||||
$customer
|
||||
// ->setCustomAttribute('is_active', $data['is_active'] ?? true)
|
||||
// ->setCustomAttribute('is_netsuite_customer', true)
|
||||
->setCustomAttribute('company_name', $data['company_name'] ?? '')
|
||||
->setCustomAttribute('netsuite_id', $data['netsuite_customer_id'] ?? '');
|
||||
|
||||
// Save customer
|
||||
$customer = $this->customerRepository->save($customer);
|
||||
|
||||
$addresses = [];
|
||||
// If shipping_address data is provided, create and associate address with customer
|
||||
$shippingAddressData = $data['shipping_address'] ?? null;
|
||||
if ($shippingAddressData && !empty($shippingAddressData['street'][0]) && !empty($shippingAddressData['city']) && !empty($shippingAddressData['postcode'])) {
|
||||
$shippingAddress = $this->addressFactory->create(['data' => $shippingAddressData]);
|
||||
$shippingAddress->setIsDefaultShipping(true);
|
||||
$addresses[] = $shippingAddress;
|
||||
}
|
||||
|
||||
// If billing_address data is provided, create and associate address with customer
|
||||
$billingAddressData = $data['billing_address'] ?? null;
|
||||
if ($billingAddressData && !empty($billingAddressData['street'][0]) && !empty($billingAddressData['city']) && !empty($billingAddressData['postcode'])) {
|
||||
$billingAddress = $this->addressFactory->create(['data' => $billingAddressData]);
|
||||
$billingAddress->setIsDefaultBilling(true);
|
||||
$addresses[] = $billingAddress;
|
||||
}
|
||||
|
||||
$customer->setAddresses($addresses);
|
||||
$customer = $this->customerRepository->save($customer);
|
||||
|
||||
return [
|
||||
'data' => $customer,
|
||||
'is_new' => true
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save NetSuite Customer ID to Magento Customer
|
||||
*
|
||||
* @param string $email
|
||||
* @param string $netsuiteCustomerId
|
||||
* @return void
|
||||
*/
|
||||
public function saveNetsuiteId(string $email, string $netsuiteCustomerId) {
|
||||
$customer = $this->customerRepository->get($email);
|
||||
$customer->setCustomAttribute('netsuite_id', $netsuiteCustomerId);
|
||||
$this->customerRepository->save($customer);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace JR\NetSuite\Service;
|
||||
|
||||
class LocationsSyncService
|
||||
{
|
||||
|
||||
protected $logger;
|
||||
|
||||
protected $helper;
|
||||
|
||||
protected $netSuiteAPI;
|
||||
|
||||
protected $locationResourceModel;
|
||||
|
||||
/**
|
||||
* @param \JR\NetSuite\Logger\Logger $logger
|
||||
* @param \JR\NetSuite\Helper\Data $helper
|
||||
* @param \JR\NetSuite\Lib\NetSuiteAPI $netSuiteAPI
|
||||
* @param \JR\NetSuite\Model\ResourceModel\Location $locationResourceModel
|
||||
*/
|
||||
public function __construct(
|
||||
\JR\NetSuite\Logger\Logger $logger,
|
||||
\JR\NetSuite\Helper\Data $helper,
|
||||
\JR\NetSuite\Lib\NetSuiteAPI $netSuiteAPI,
|
||||
\JR\NetSuite\Model\ResourceModel\Location $locationResourceModel
|
||||
) {
|
||||
$this->logger = $logger;
|
||||
$this->helper = $helper;
|
||||
$this->netSuiteAPI = $netSuiteAPI;
|
||||
$this->locationResourceModel = $locationResourceModel;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function sync()
|
||||
{
|
||||
$result = [
|
||||
'error' => false,
|
||||
'message' => 'Locations saved successfully.'
|
||||
];
|
||||
|
||||
$this->logger->info('Start Locations Sync');
|
||||
|
||||
$this->logger->info('Fetching locations from NetSuite');
|
||||
|
||||
$locations = $this->netSuiteAPI->fetchLocations();
|
||||
|
||||
if (isset($locations['error'])) {
|
||||
$result['error'] = true;
|
||||
$result['message'] = $locations['message'];
|
||||
$this->logger->info('Error while fetching locations from NetSuite: ' . $locations['message']);
|
||||
return $result;
|
||||
}
|
||||
|
||||
$this->logger->info('Locations fetched successfully');
|
||||
|
||||
$this->logger->info('Start saving locations');
|
||||
|
||||
$this->locationResourceModel->saveLocations($locations['data']);
|
||||
|
||||
$this->logger->info('Locations saved successfully');
|
||||
|
||||
$this->logger->info('End Locations Sync');
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,771 @@
|
||||
<?php
|
||||
|
||||
namespace JR\NetSuite\Service;
|
||||
|
||||
|
||||
use Magento\Customer\Model\AddressFactory;
|
||||
use Magento\Quote\Model\Quote;
|
||||
use Magento\Quote\Model\QuoteFactory;
|
||||
use Magento\Quote\Model\QuoteManagement;
|
||||
use Magento\Quote\Model\Quote\Address\Rate;
|
||||
use Magento\Quote\Api\CartRepositoryInterface;
|
||||
use Magento\Quote\Api\CartManagementInterface;
|
||||
use Magento\Quote\Api\Data\AddressExtensionInterfaceFactory;
|
||||
use Magento\Quote\Api\Data\AddressInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Magento\CatalogInventory\Api\StockRegistryInterface;
|
||||
use Magento\Catalog\Api\ProductRepositoryInterface;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Api\SearchCriteriaBuilder;
|
||||
use Magento\Sales\Api\OrderRepositoryInterface;
|
||||
use Magento\Sales\Api\Data\OrderInterface;
|
||||
use Magento\Sales\Model\OrderFactory;
|
||||
use Magento\InventoryApi\Api\SourceRepositoryInterface;
|
||||
use Magento\InventoryCatalog\Model\GetStockIdForCurrentWebsite;
|
||||
use Magento\InventoryReservationsApi\Model\GetReservationsQuantityInterface;
|
||||
use JR\Netsuite\Mapper\OrderMapper;
|
||||
|
||||
|
||||
class OrdersSyncService {
|
||||
|
||||
const TAX_GROUP = 'TaxGroup';
|
||||
const SHIP_ITEM = 'ShipItem';
|
||||
const INVT_PART = 'InvtPart';
|
||||
const DISCOUNT = 'Discount';
|
||||
|
||||
/**
|
||||
* @var \Magento\Customer\Model\AddressFactory
|
||||
*/
|
||||
protected $addressFactory;
|
||||
|
||||
/**
|
||||
* @var \Magento\Quote\Model\QuoteFactory
|
||||
*/
|
||||
protected $quoteFactory;
|
||||
|
||||
/**
|
||||
* @var \Magento\Quote\Model\QuoteManagement
|
||||
*/
|
||||
protected $quoteManagement;
|
||||
|
||||
/**
|
||||
* @var \Magento\Quote\Api\CartRepositoryInterface
|
||||
*/
|
||||
protected $cartRepository;
|
||||
|
||||
/**
|
||||
* @var \Magento\Quote\Api\CartManagementInterface
|
||||
*/
|
||||
protected $cartManagement;
|
||||
|
||||
/**
|
||||
* @var \Magento\Store\Model\StoreManagerInterface
|
||||
*/
|
||||
protected $storeManager;
|
||||
|
||||
/**
|
||||
* @var \Magento\CatalogInventory\Api\StockRegistryInterface
|
||||
*/
|
||||
protected $stockRegistry;
|
||||
|
||||
/**
|
||||
* @var GetStockIdForCurrentWebsite
|
||||
*/
|
||||
protected $getStockIdForCurrentWebsite;
|
||||
|
||||
/**
|
||||
* @var GetReservationsQuantityInterface
|
||||
*/
|
||||
protected $getReservationsQuantity;
|
||||
|
||||
/**
|
||||
* @var CustomersSyncService
|
||||
*/
|
||||
protected $customersSyncService;
|
||||
|
||||
/**
|
||||
* @var OrderMapper
|
||||
*/
|
||||
protected $orderMapper;
|
||||
|
||||
/**
|
||||
* @var SourceRepositoryInterface
|
||||
*/
|
||||
protected $sourceRepository;
|
||||
|
||||
/**
|
||||
* @var \Magento\Catalog\Api\ProductRepositoryInterface
|
||||
*/
|
||||
protected $productRepository;
|
||||
|
||||
/**
|
||||
* @var \Magento\Sales\Api\OrderRepositoryInterface
|
||||
*/
|
||||
protected $orderRepository;
|
||||
|
||||
/**
|
||||
* @var \Magento\Sales\Model\OrderFactory
|
||||
*/
|
||||
protected $orderFactory;
|
||||
|
||||
/**
|
||||
* @var \Magento\Framework\Api\SearchCriteriaBuilder
|
||||
*/
|
||||
protected $searchCriteriaBuilder;
|
||||
|
||||
/**
|
||||
* @var \Magento\Quote\Api\Data\AddressExtensionInterfaceFactory
|
||||
*/
|
||||
protected $addressExtensionFactory;
|
||||
|
||||
/**
|
||||
* @var \Magento\Quote\Model\Quote\Address\Rate
|
||||
*/
|
||||
private $shippingRate;
|
||||
|
||||
/**
|
||||
* @var ProductsSyncService
|
||||
*/
|
||||
protected $productsSync;
|
||||
|
||||
/**
|
||||
* @var \JR\NetSuite\Helper\Data
|
||||
*/
|
||||
|
||||
protected $helper;
|
||||
|
||||
/**
|
||||
* @var \JR\NetSuite\Logger\Logger
|
||||
*/
|
||||
protected $logger;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $defaultStoreId;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $productStocks = [];
|
||||
|
||||
/**
|
||||
* OrdersSyncService constructor.
|
||||
* @param AddressFactory $addressFactory
|
||||
* @param QuoteFactory $quoteFactory
|
||||
* @param QuoteManagement $quoteManagement
|
||||
* @param CartRepositoryInterface $cartRepository
|
||||
* @param CartManagementInterface $cartManagement
|
||||
* @param StoreManagerInterface $storeManager
|
||||
* @param StockRegistryInterface $stockRegistry
|
||||
* @param GetStockIdForCurrentWebsite $getStockIdForCurrentWebsite
|
||||
* @param GetReservationsQuantityInterface $getReservationsQuantity
|
||||
* @param CustomersSyncService $customersSyncService
|
||||
* @param OrderMapper $orderMapper
|
||||
* @param SourceRepositoryInterface $sourceRepository
|
||||
* @param ProductRepositoryInterface $productRepository
|
||||
* @param OrderRepositoryInterface $orderRepository
|
||||
* @param OrderFactory $orderFactory
|
||||
* @param SearchCriteriaBuilder $searchCriteriaBuilder
|
||||
* @param AddressExtensionInterfaceFactory $addressExtensionFactory
|
||||
* @param Rate $shippingRate
|
||||
* @param ProductsSyncService $productsSync
|
||||
* @param \JR\NetSuite\Helper\Data $helper
|
||||
* @param \JR\NetSuite\Logger\Logger $logger
|
||||
*/
|
||||
public function __construct(
|
||||
AddressFactory $addressFactory,
|
||||
QuoteFactory $quoteFactory,
|
||||
QuoteManagement $quoteManagement,
|
||||
CartRepositoryInterface $cartRepository,
|
||||
CartManagementInterface $cartManagement,
|
||||
StoreManagerInterface $storeManager,
|
||||
StockRegistryInterface $stockRegistry,
|
||||
GetStockIdForCurrentWebsite $getStockIdForCurrentWebsite,
|
||||
GetReservationsQuantityInterface $getReservationsQuantity,
|
||||
CustomersSyncService $customersSyncService,
|
||||
OrderMapper $orderMapper,
|
||||
SourceRepositoryInterface $sourceRepository,
|
||||
ProductRepositoryInterface $productRepository,
|
||||
OrderRepositoryInterface $orderRepository,
|
||||
OrderFactory $orderFactory,
|
||||
SearchCriteriaBuilder $searchCriteriaBuilder,
|
||||
AddressExtensionInterfaceFactory $addressExtensionFactory,
|
||||
Rate $shippingRate,
|
||||
ProductsSyncService $productsSync,
|
||||
\JR\NetSuite\Helper\Data $helper,
|
||||
\JR\NetSuite\Logger\Logger $logger
|
||||
) {
|
||||
$this->addressFactory = $addressFactory;
|
||||
$this->quoteFactory = $quoteFactory;
|
||||
$this->quoteManagement = $quoteManagement;
|
||||
$this->cartRepository = $cartRepository;
|
||||
$this->cartManagement = $cartManagement;
|
||||
$this->storeManager = $storeManager;
|
||||
$this->stockRegistry = $stockRegistry;
|
||||
$this->getStockIdForCurrentWebsite = $getStockIdForCurrentWebsite;
|
||||
$this->getReservationsQuantity = $getReservationsQuantity;
|
||||
$this->customersSyncService = $customersSyncService;
|
||||
$this->orderMapper = $orderMapper;
|
||||
$this->sourceRepository = $sourceRepository;
|
||||
$this->productRepository = $productRepository;
|
||||
$this->orderRepository = $orderRepository;
|
||||
$this->orderFactory = $orderFactory;
|
||||
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
|
||||
$this->addressExtensionFactory = $addressExtensionFactory;
|
||||
$this->shippingRate = $shippingRate;
|
||||
$this->productsSync = $productsSync;
|
||||
$this->helper = $helper;
|
||||
$this->logger = $logger;
|
||||
$this->defaultStoreId = $this->helper->getDefaultStoreId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or Skip a order based on the provided data
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function createOrSkip(array $data) {
|
||||
$order = $this->orderMapper->getOrderBy('netsuite_id', $data['netsuite_order_id']);
|
||||
if ($order) {
|
||||
return [
|
||||
'data' => $order,
|
||||
'is_new' => false
|
||||
];
|
||||
}
|
||||
|
||||
$order = $this->create($data);
|
||||
return [
|
||||
'data' => $order,
|
||||
'is_new' => true
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or Update a order based on the provided data. Only update status for now. TODO: Update other order attributes including item, price etc.
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function createOrUpdate(array $data) {
|
||||
// $this->logger->info("[OrdersSyncService] createOrUpdate: " . json_encode($data));
|
||||
$order = $this->orderMapper->getOrderBy('netsuite_id', $data['netsuite_order_id']);
|
||||
|
||||
if ($order) {
|
||||
$this->updateOrderStatus($order, $data['status']);
|
||||
return [
|
||||
'data' => $order,
|
||||
'is_new' => false
|
||||
];
|
||||
}
|
||||
|
||||
$order = $this->create($data);
|
||||
return [
|
||||
'data' => $order,
|
||||
'is_new' => true
|
||||
];
|
||||
}
|
||||
|
||||
private function updateOrderStatus($order, $newStatus) {
|
||||
$currentStatus = $order->getStatus();
|
||||
if ($currentStatus === $newStatus) {
|
||||
// $this->logger->info("[OrdersSyncService] updateOrderStatus: Order #" . $order->getIncrementId() . " is already in status '$currentStatus'. No change needed.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Map status ? state
|
||||
$statusStateMap = [
|
||||
'pending' => \Magento\Sales\Model\Order::STATE_NEW,
|
||||
'processing' => \Magento\Sales\Model\Order::STATE_PROCESSING,
|
||||
'complete' => \Magento\Sales\Model\Order::STATE_COMPLETE,
|
||||
'canceled' => \Magento\Sales\Model\Order::STATE_CANCELED,
|
||||
'closed' => \Magento\Sales\Model\Order::STATE_CLOSED,
|
||||
'holded' => \Magento\Sales\Model\Order::STATE_HOLDED,
|
||||
'payment_review' => \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW,
|
||||
];
|
||||
|
||||
$newState = $statusStateMap[$newStatus] ?? null;
|
||||
if (!$newState) {
|
||||
$this->logger->error("[OrdersSyncService] updateOrderStatus: Unknown status '$newStatus'.");
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$order->setStatus($newStatus);
|
||||
$order->setState($newState);
|
||||
|
||||
$this->orderRepository->save($order);
|
||||
|
||||
// $this->logger->info("[OrdersSyncService] updateOrderStatus: Order #" . $order->getIncrementId() . " updated from status '$currentStatus' to '$newStatus' (state: '$newState').");
|
||||
return true;
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$this->logger->error("[OrdersSyncService] updateOrderStatus: Error updating order -> " . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or Update a order based on the provided data
|
||||
*
|
||||
* @param array $data
|
||||
* @return OrderInterface
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function create(array $data) {
|
||||
$quote = $this->buildQuote($data);
|
||||
$order = $this->quoteManagement->submit($quote);
|
||||
$order = $this->orderRepository->get($order->getId());
|
||||
$order->setStatus($data['status'])
|
||||
->setState($data['status'])
|
||||
->setCreatedAt($data['purchase_date'])
|
||||
->setEmailSent(0)
|
||||
->setNetsuiteId($data['netsuite_order_id'])
|
||||
->setNetsuiteNumber($data['netsuite_order_number'])
|
||||
->setIsNetsuiteSync(!empty($data['netsuite_order_number']));
|
||||
$this->addDiscount($order, $data['items']);
|
||||
$this->addTax($order, $data['items']);
|
||||
$this->addShipping($order, $data['items']);
|
||||
$this->orderRepository->save($order);
|
||||
$this->afterOrderSave();
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return Quote
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
private function buildQuote(array $data): Quote {
|
||||
$quote = $this->initQuote($data);
|
||||
$quote = $this->addItems($quote, $data['items']);
|
||||
$quote = $this->setAddresses($quote, $data);
|
||||
$quote = $this->setPayment($quote, $data['payment']['method'] ?? 'checkmo');
|
||||
$quote->setInventoryProcessed(false);
|
||||
$quote->setTotalsCollectedFlag(false);
|
||||
$quote->collectTotals();
|
||||
// $this->addTax($quote, $data['items']);
|
||||
// $quote->setTaxAmount($data['tax']);
|
||||
// $quote->setBaseTaxAmount($data['tax']);
|
||||
$this->cartRepository->save($quote);
|
||||
|
||||
return $quote;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return Quote
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
private function initQuote(array $data): Quote {
|
||||
$store = $this->storeManager->getStore($this->defaultStoreId);
|
||||
$websiteId = $store->getWebsiteId();
|
||||
// get the customer by email
|
||||
$customer = $this->getOrCreateCustomer($data, $websiteId);
|
||||
$cartId = $this->cartManagement->createEmptyCart();
|
||||
$quote = $this->cartRepository->get($cartId);
|
||||
|
||||
$quote->setStore($store);
|
||||
$quote->setCurrency();
|
||||
$quote->assignCustomer($customer);
|
||||
if ($quote->getCustomer()->getId()) {
|
||||
$quote->setCustomerIsGuest(0);
|
||||
}
|
||||
|
||||
// Write PO Number
|
||||
$quote->setOtherRefNum($data['other_ref_num']);
|
||||
|
||||
// Set custom data
|
||||
$quote->setData('netsuite_order_id', $data['netsuite_order_id']);
|
||||
|
||||
return $quote;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @param int $websiteId
|
||||
* @return \Magento\Customer\Api\Data\CustomerInterface
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
private function getOrCreateCustomer(array $data, int $websiteId) {
|
||||
if (empty($data['firstname'])) $data['firstname'] = $data['shipping_address']['firstname'] ?? $data['billing_address']['firstname'] ?? '';
|
||||
if (empty($data['lastname'])) $data['lastname'] = $data['shipping_address']['lastname'] ?? $data['billing_address']['lastname'] ?? '';
|
||||
|
||||
$customerData = $data;
|
||||
if (isset($data['customer'])) {
|
||||
if (count($data['customer']) == 1) $data['customer'] = reset($data['customer']);
|
||||
if (($data['customer']['email'] ?? '') == '') $data['customer']['email'] = $data['email'];
|
||||
$customerData = $data['customer'];
|
||||
}
|
||||
if (empty($data['firstname'])) $data['firstname'] = $data['shipping_address']['firstname'] ?? $data['billing_address']['firstname'] ?? $customerData['firstname'] ?? '';
|
||||
if (empty($data['lastname'])) $data['lastname'] = $data['shipping_address']['lastname'] ?? $data['billing_address']['lastname'] ?? $customerData['lastname'] ?? '';
|
||||
|
||||
$result = $this->customersSyncService->createOrSkip($customerData);
|
||||
|
||||
return $result['data'];
|
||||
|
||||
// try {
|
||||
// $customer = $this->customerRepository->get($data['email'], $websiteId);
|
||||
// } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
|
||||
// $customer = $this->customerFactory->create();
|
||||
// }
|
||||
// if (!$customer->getId()) {
|
||||
// $customer->setWebsiteId($websiteId)
|
||||
// ->setFirstname($data['shipping_address']['firstname'])
|
||||
// ->setLastname($data['shipping_address']['lastname'])
|
||||
// ->setEmail($data['email']);
|
||||
// $customer = $this->customerRepository->save($customer);
|
||||
// }
|
||||
// return $customer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Quote $quote
|
||||
* @param Quote $quote
|
||||
* @return Quote
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
private function addItems(Quote $quote, array $items = []): Quote {
|
||||
$productNameError = '';
|
||||
foreach ($items as $item) {
|
||||
if ($item['type'] != self::INVT_PART) continue;
|
||||
$product = $this->productRepository->get($item['sku']);
|
||||
// need to be changed if multi location
|
||||
// Product stock is being synced by cronjob, ProductSyncWorker::processQueueItems. There is no need to touch stock during order sync
|
||||
/*
|
||||
$stockDetail = $this->productsSync->updateStockForProduct($item['sku'], $item, $product->getStore()->getWebsiteId());
|
||||
$this->productStocks[$item['sku']] = $stockDetail;
|
||||
*/
|
||||
$stockItem = $this->stockRegistry->getStockItem($product->getId());
|
||||
$qty = (int) $stockItem->getQty() + $item['qty'];
|
||||
$stockId = $this->getStockIdForCurrentWebsite->execute();
|
||||
$qty -= $this->getReservationsQuantity->execute($item['sku'], $stockId);
|
||||
$stockItem->setData('is_in_stock', 1);
|
||||
$stockItem->setData('qty', $qty);
|
||||
$stockItem->setData('manage_stock', 1);
|
||||
$stockItem->setData('use_config_notify_stock_qty', 1);
|
||||
$stockItem->save();
|
||||
// $status = $product->getStatus();
|
||||
// $salable = $product->getData('salable');
|
||||
$product->setOrigData('status', 1);
|
||||
$product->setStatus(1);
|
||||
$product->setData('salable', true);
|
||||
$product->setPrice($item['price']);
|
||||
$discountAmount = ((float)$item['amount'] - (float)$item['price'] * $item['qty']) / $item['qty'];
|
||||
// $product->setSpecialPrice($item['price'] + $discountAmount);
|
||||
$productNameError = $productNameError . ' ' . $product->getName() . '( SKU : ' . $product->getSku() . ')';
|
||||
// $this->logger->info($product->getSku() . ' ' . $item['qty']);
|
||||
$quoteItem = $quote->addProduct($product, (int) $item['qty']);
|
||||
// $product->setStatus($status);
|
||||
// $product->setData('salable', $salable);
|
||||
// $product->save();
|
||||
// $quoteItem->setTaxPercent($quote->getTaxPercent());
|
||||
// $quoteItem->setTaxAmount($item['amount'] * $quote->getTaxPercent() / 100);
|
||||
// $quoteItem->setBaseTaxAmount($item['amount'] * $quote->getTaxPercent() / 100);
|
||||
// $quoteItem->setDiscountAmount($discountAmount);
|
||||
// $quoteItem->setBaseDiscountAmount($discountAmount);
|
||||
// $quoteItem->setSubtotal($item['price'] * $item['qty']);
|
||||
// $quoteItem->setBaseSubtotal($item['price'] * $item['qty']);
|
||||
// $quoteItem->setRowTotal($item['amount']);
|
||||
// $quoteItem->setBaseRowTotal($item['amount']);
|
||||
$quoteItem->setCustomPrice($item['price']);
|
||||
$quoteItem->setOriginalCustomPrice($item['price']);
|
||||
$quoteItem->getProduct()->setIsSuperMode(true);
|
||||
}
|
||||
return $quote;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param OrderInterface $order
|
||||
* @param array $items
|
||||
*/
|
||||
private function addDiscount(OrderInterface $order, array $items): void {
|
||||
$discount = 0;
|
||||
$discountDescription = '';
|
||||
$itemMap = [];
|
||||
foreach ($items as $item) {
|
||||
if ($item['type'] == self::DISCOUNT) {
|
||||
$discount += $item['amount'];
|
||||
$discountDescription = $item['sku'];
|
||||
} else {
|
||||
$itemMap[$item['sku']] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
if ($discount == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$order->setDiscountAmount($discount);
|
||||
$order->setBaseDiscountAmount($discount);
|
||||
$order->setDiscountDescription($discountDescription);
|
||||
$order->setGrandTotal($order->getGrandTotal() + $discount);
|
||||
$order->setBaseGrandTotal($order->getBaseGrandTotal() + $discount);
|
||||
|
||||
foreach ($order->getAllItems() as $item) {
|
||||
if ($item) {
|
||||
$itemData = $itemMap[$item->getSku()];
|
||||
$discountAmount = $itemData['price'] * $itemData['qty'] - $itemData['amount'];
|
||||
$discountRate = $itemData['price'] == 0 ? 0 : $discountAmount / ($itemData['price'] * $itemData['qty']) * 100;
|
||||
$item->setDiscountPercent($discountRate);
|
||||
$item->setDiscountAmount($discountAmount);
|
||||
$item->setBaseDiscountAmount($discountAmount);
|
||||
$item->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param OrderInterface $order
|
||||
* @param array $items
|
||||
*/
|
||||
private function addTax(OrderInterface $order, array $items): void {
|
||||
$tax = 0;
|
||||
$taxRate = 0;
|
||||
foreach ($items as $item) {
|
||||
if ($item['type'] == self::TAX_GROUP) {
|
||||
$tax += $item['amount'];
|
||||
$taxRate += $item['price'];
|
||||
}
|
||||
}
|
||||
|
||||
if ($tax <= 0) {
|
||||
return;
|
||||
}
|
||||
// $order->setTaxPercent($taxRate);
|
||||
$order->setTaxAmount($tax);
|
||||
$order->setBaseTaxAmount($tax);
|
||||
$order->setGrandTotal($order->getGrandTotal() + $tax);
|
||||
$order->setBaseGrandTotal($order->getBaseGrandTotal() + $tax);
|
||||
|
||||
foreach ($order->getAllItems() as $item) {
|
||||
if ($item) {
|
||||
$item->setTaxPercent($taxRate);
|
||||
$taxAmount = $item->getPrice() * $item->getQtyOrdered() * $taxRate / 100;
|
||||
$item->setTaxAmount($taxAmount);
|
||||
$item->setBaseTaxAmount($taxAmount);
|
||||
$priceInclTax = $item->getPrice() + $item->getPrice() * $taxRate / 100;
|
||||
$item->setPriceInclTax($priceInclTax);
|
||||
$item->setBasePriceInclTax($priceInclTax);
|
||||
$item->setRowTotalInclTax($item->getRowTotal() + $item->getTaxAmount());
|
||||
$item->setBaseRowTotalInclTax($item->getBaseRowTotal() + $item->getBaseTaxAmount());
|
||||
$item->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Quote $quote
|
||||
* @param array $data
|
||||
* @return Quote
|
||||
*/
|
||||
private function setAddresses(Quote $quote, array $data): Quote {
|
||||
if (!isset($data['shipping_address']) || empty($data['shipping_address'])) {
|
||||
if (isset($data['customer']) && ($data['customer']['isdefaultshipping'] ?? false)) {
|
||||
$data['shipping_address'] = $data['customer']['shipping_address'];
|
||||
} else if ($shippingAddressId = $quote->getCustomer()->getDefaultShipping()) {
|
||||
$shippingAddress = $this->addressFactory->create()->load($shippingAddressId);
|
||||
$data['shipping_address'] = $shippingAddress->getData();
|
||||
} else if (isset($data['customer'][0]['shipping_address'])) {
|
||||
$data['shipping_address'] = $data['customer'][0]['shipping_address'];
|
||||
}
|
||||
} else {
|
||||
if ($data['shipping_address']['firstname'] == '') {
|
||||
if (isset($data['customer'])) {
|
||||
$data['shipping_address']['firstname'] = $data['customer']['firstname'];
|
||||
} else {
|
||||
$data['shipping_address']['firstname'] = $quote->getCustomer()->getFirstname();
|
||||
}
|
||||
}
|
||||
if ($data['shipping_address']['lastname'] == '') {
|
||||
if (isset($data['customer'])) {
|
||||
$data['shipping_address']['lastname'] = $data['customer']['lastname'];
|
||||
} else {
|
||||
$data['shipping_address']['lastname'] = $quote->getCustomer()->getLastname();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($data['billing_address']) || empty($data['billing_address'])) {
|
||||
if (isset($data['customer']) && ($data['customer']['isdefaultbilling'] ?? false)) {
|
||||
$data['billing_address'] = $data['customer']['billing_address'];
|
||||
} else if ($billingAddressId = $quote->getCustomer()->getDefaultBilling()) {
|
||||
$billingAddress = $this->addressFactory->create()->load($billingAddressId);
|
||||
$data['billing_address'] = $billingAddress->getData();
|
||||
unset($data['billing_address']['entity_id']);
|
||||
} else if (isset($data['customer'][0]['billing_address'])) {
|
||||
$data['billing_address'] = $data['customer'][0]['billing_address'];
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($data['shipping_address']) && !$data['shipping_address']['company']) $data['shipping_address']['company'] = $data['company'];
|
||||
if (isset($data['billing_address']) && !$data['billing_address']['company']) $data['billing_address']['company'] = $data['company'];
|
||||
$quote->getBillingAddress()->addData($data['billing_address'] ?? $data['shipping_address'] ?? []);
|
||||
$shippingAddress = $quote->getShippingAddress()
|
||||
->addData($data['shipping_address'] ?? $data['billing_address'] ?? []);
|
||||
// $shippingAddress->getShippingRateByCode($shippingAddress->getShippingMethod());
|
||||
$shippingItem = $this->getShippingItem($data['items']);
|
||||
$shippingItem['sku'] = $shippingItem['sku'] ?? '';
|
||||
$this->shippingRate->setCode($shippingItem['sku'])
|
||||
->setPrice($shippingItem['amount'] ?? 0);
|
||||
|
||||
if (strpos(strtolower($shippingItem['sku']), 'ups') !== false) {
|
||||
$shippingAddress->setShippingMethod('ups');
|
||||
} else if (strpos(strtolower($shippingItem['sku']), 'fedex') !== false) {
|
||||
$shippingAddress->setShippingMethod('fedex');
|
||||
} else {
|
||||
$shippingAddress->setShippingMethod('flatrate_flatrate');
|
||||
}
|
||||
|
||||
$m2ShipMethod = $this->orderMapper->parseNetSuiteShippingMethod($shippingItem['netsuite_order_item_id'] ?? '');
|
||||
$this->logger->info("Shipping Method: " . $shippingItem['netsuite_order_item_id'] . " -> " . $m2ShipMethod);
|
||||
if ($m2ShipMethod == 'instore_pickup') {
|
||||
$pickupLocationCode = $this->getPickupLocationSourceCode($data['netsuite_order_location_id']);
|
||||
$pickupSource = $this->sourceRepository->get($pickupLocationCode);
|
||||
$this->logger->info("Pickup Location: {$pickupLocationCode}");
|
||||
|
||||
$street = $pickupSource->getStreet();
|
||||
if (!is_array($street)) {
|
||||
$street = [$street];
|
||||
}
|
||||
|
||||
$shippingAddress->setShippingMethod($m2ShipMethod)
|
||||
->setFirstname($data['shipping_address']['firstname'])
|
||||
->setLastname($data['shipping_address']['lastname'])
|
||||
->setSameAsBilling(false) // ***
|
||||
->setStreet($street) // ***
|
||||
->setCity($pickupSource->getCity()) // ***
|
||||
->setRegionId($pickupSource->getRegionId()) // ***
|
||||
->setRegion($pickupSource->getRegion()) // ***
|
||||
->setPostcode($pickupSource->getPostcode()) // ***
|
||||
->setCountryId($pickupSource->getCountryId()) // ***
|
||||
->setTelephone($data['shipping_address']['telephone'] ?? '000-000-0000')
|
||||
->setShippingDescription("In-Store Pickup Delivery - {$pickupSource->getName()}");
|
||||
|
||||
$extensionAttributes = $shippingAddress->getExtensionAttributes();
|
||||
if (!$extensionAttributes) {
|
||||
$extensionAttributes = $this->addressExtensionFactory->create();
|
||||
}
|
||||
$extensionAttributes->setPickupLocationCode($pickupLocationCode);
|
||||
$shippingAddress->setExtensionAttributes($extensionAttributes);
|
||||
} else {
|
||||
$shippingAddress->setCollectShippingRates(true)
|
||||
->setShippingMethod($m2ShipMethod)
|
||||
->collectShippingRates();
|
||||
$shippingAmount = (float) $shippingItem['amount'];
|
||||
$quote->getShippingAddress()
|
||||
->setShippingAmount($shippingAmount)
|
||||
->setBaseShippingAmount((float) $shippingItem['amount'])
|
||||
->setShippingDescription($shippingItem['sku']);
|
||||
$quote->getShippingAddress()->addShippingRate($this->shippingRate);
|
||||
}
|
||||
|
||||
// $shippingAddress->setCollectShippingRates(true)
|
||||
// ->setShippingMethod('ups_03')
|
||||
// ->collectShippingRates();
|
||||
// $shippingAmount = (float) $shippingItem['amount'];
|
||||
// $quote->getShippingAddress()
|
||||
// ->setShippingAmount($shippingAmount)
|
||||
// ->setBaseShippingAmount((float) $shippingItem['amount'])
|
||||
// ->setShippingDescription($shippingItem['sku']);
|
||||
// $quote->getShippingAddress()->addShippingRate($this->shippingRate);
|
||||
|
||||
$quote->getBillingAddress()->setCustomerAddressId(null);
|
||||
$quote->getShippingAddress()->setCustomerAddressId(null);
|
||||
|
||||
return $quote;
|
||||
}
|
||||
|
||||
/**
|
||||
* get shipping item
|
||||
*
|
||||
* @param array $items
|
||||
* @return array
|
||||
*/
|
||||
private function getShippingItem(array $items): array {
|
||||
foreach ($items as $item) {
|
||||
if ($item['type'] === self::SHIP_ITEM && $item['price']) {
|
||||
return $item;
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* set shipping to order
|
||||
*
|
||||
* @param OrderInterface $order
|
||||
* @param array $items
|
||||
*/
|
||||
private function addShipping(OrderInterface $order, array $items) {
|
||||
$shippingItem = $this->getShippingItem($items);
|
||||
$originShippingAmount = $order->getShippingAmount();
|
||||
$order->setShippingAmount($shippingItem['amount']);
|
||||
$order->setBaseShippingAmount($shippingItem['amount']);
|
||||
$order->setShippingDescription($shippingItem['sku']);
|
||||
$grandTotal = $order->getGrandTotal() - $originShippingAmount + $shippingItem['amount'];
|
||||
$order->setGrandTotal($grandTotal);
|
||||
$order->setBaseGrandTotal($grandTotal);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Quote $quote
|
||||
* @param string $paymentMethod
|
||||
* @return Quote
|
||||
*/
|
||||
private function setPayment(Quote $quote, string $paymentMethod): Quote {
|
||||
if (!$paymentMethod || $paymentMethod == '') {
|
||||
$paymentMethod = 'checkmo';
|
||||
}
|
||||
$quote->setPaymentMethod($paymentMethod);
|
||||
$quote->getPayment()->importData(['method' => $paymentMethod]);
|
||||
return $quote;
|
||||
}
|
||||
|
||||
public function afterOrderSave() {
|
||||
// Product stock is being synced by cronjob, ProductSyncWorker::processQueueItems. There is no need to touch stock during order sync
|
||||
// If for some reason need to uncomment the below, also need to uncomment the part inside addItems()
|
||||
/*
|
||||
foreach ($this->productStocks as $sku => $stockDetail) {
|
||||
$stockDetail['qty'] = $stockDetail['from'];
|
||||
$this->productsSync->updateStockForProduct($sku, $stockDetail);
|
||||
}
|
||||
$this->productStocks = [];
|
||||
*/
|
||||
}
|
||||
|
||||
/**
|
||||
* Save NetSuite Order ID to Magento Order
|
||||
*
|
||||
* @param OrderInterface $order
|
||||
* @param string $netsuiteOrderId
|
||||
* @return void
|
||||
*/
|
||||
public function saveNetsuiteId(OrderInterface $order, string $netsuiteOrderId) {
|
||||
$order->setNetsuiteId($netsuiteOrderId);
|
||||
$this->orderRepository->save($order);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search inventory source code by NetSuite location id.
|
||||
*
|
||||
* @param string $nsLocationId
|
||||
* @return string
|
||||
*/
|
||||
private function getPickupLocationSourceCode($nsLocationId) {
|
||||
$searchCriteria = $this->searchCriteriaBuilder
|
||||
->addFilter('netsuite_id', $nsLocationId)
|
||||
->create();
|
||||
$sources = $this->sourceRepository->getList($searchCriteria)->getItems();
|
||||
if (count($sources) > 0) {
|
||||
$source = reset($sources);
|
||||
return $source->getSourceCode() ?? '';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+428
@@ -0,0 +1,428 @@
|
||||
<?php
|
||||
|
||||
namespace JR\NetSuite\Service;
|
||||
|
||||
use Magento\Catalog\Model\Product\Type as ProductType;
|
||||
use Magento\Catalog\Model\Product\Attribute\Source\Status as ProductStatus;
|
||||
use JR\NetSuite\Service\AttributesSyncService as AttributesSync;
|
||||
use Magento\InventoryApi\Api\Data\SourceItemInterface;
|
||||
use Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory;
|
||||
use Magento\InventoryApi\Api\SourceItemsSaveInterface;
|
||||
use Magento\InventoryApi\Api\GetSourceItemsBySkuInterface;
|
||||
use Magento\InventoryCatalog\Model\GetStockIdForCurrentWebsite;
|
||||
use Magento\InventoryReservationsApi\Model\GetReservationsQuantityInterface;
|
||||
use JR\NetSuite\Model\ResourceModel\Location\CollectionFactory as LocationCollectionFactory;
|
||||
|
||||
class ProductsSyncService {
|
||||
|
||||
protected $logger;
|
||||
protected $productFactory;
|
||||
protected $eavAttributeRepository;
|
||||
protected $resourceConnection;
|
||||
protected $productRepository;
|
||||
protected $registry;
|
||||
protected $transactionFactory;
|
||||
protected $stockItemRepository;
|
||||
protected $sourceItemFactory;
|
||||
protected $sourceItemsSave;
|
||||
protected $getSourceItemsBySku;
|
||||
protected $getStockIdForCurrentWebsite;
|
||||
protected $getReservationsQuantity;
|
||||
protected $locationCollectionFactory;
|
||||
|
||||
protected $helper;
|
||||
protected $visibility;
|
||||
protected $defaultTaxClass;
|
||||
protected $attributesSync;
|
||||
protected $storeId;
|
||||
protected $storeUrlKeys;
|
||||
|
||||
public function __construct(
|
||||
\JR\NetSuite\Logger\Logger $logger,
|
||||
\Magento\Catalog\Model\ProductFactory $productFactory,
|
||||
\JR\NetSuite\Helper\Data $helper,
|
||||
AttributesSync $attributesSync,
|
||||
\Magento\Eav\Api\AttributeRepositoryInterface $eavAttributeRepository,
|
||||
\Magento\Framework\App\ResourceConnection $resourceConnection,
|
||||
\Magento\Catalog\Model\ProductRepository $productRepository,
|
||||
\Magento\Framework\Registry $registry,
|
||||
\Magento\Framework\DB\TransactionFactory $transactionFactory,
|
||||
\Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository,
|
||||
SourceItemInterfaceFactory $sourceItemFactory,
|
||||
SourceItemsSaveInterface $sourceItemsSave,
|
||||
GetSourceItemsBySkuInterface $getSourceItemsBySku,
|
||||
GetStockIdForCurrentWebsite $getStockIdForCurrentWebsite,
|
||||
GetReservationsQuantityInterface $getReservationsQuantity,
|
||||
LocationCollectionFactory $locationCollectionFactory
|
||||
) {
|
||||
$this->storeId = \Magento\Store\Model\Store::DEFAULT_STORE_ID;
|
||||
$this->logger = $logger;
|
||||
$this->transactionFactory = $transactionFactory;
|
||||
|
||||
$this->productFactory = $productFactory;
|
||||
$this->stockItemRepository = $stockItemRepository;
|
||||
$this->sourceItemFactory = $sourceItemFactory;
|
||||
$this->sourceItemsSave = $sourceItemsSave;
|
||||
$this->getSourceItemsBySku = $getSourceItemsBySku;
|
||||
$this->getStockIdForCurrentWebsite = $getStockIdForCurrentWebsite;
|
||||
$this->getReservationsQuantity = $getReservationsQuantity;
|
||||
$this->locationCollectionFactory = $locationCollectionFactory;
|
||||
|
||||
$this->helper = $helper;
|
||||
$this->attributesSync = $attributesSync;
|
||||
$this->eavAttributeRepository = $eavAttributeRepository;
|
||||
$this->resourceConnection = $resourceConnection;
|
||||
|
||||
$this->productRepository = $productRepository;
|
||||
$this->registry = $registry;
|
||||
|
||||
$this->visibility = $this->helper->getDefaultVisibilityId();
|
||||
$this->defaultTaxClass = $this->helper->getDefaultTaxClass();
|
||||
|
||||
$this->initStoreUrlKeys();
|
||||
}
|
||||
|
||||
/**
|
||||
* This builds up the product keys in memory for us to check if for duplicate URLs
|
||||
*
|
||||
* Dear other developers, I wasn't sure how to get all the actual values of $attribute based on store ID.
|
||||
* Maybe I missed something but I couldn't find what method I should use to retrieve this information using the
|
||||
* attribute model below ($attribute). In the meantime I'm just doing a simple select.
|
||||
*
|
||||
*/
|
||||
public function initStoreUrlKeys() {
|
||||
$this->storeUrlKeys = [];
|
||||
|
||||
// Get the 'url_key' attribute for products.
|
||||
$attribute = $this->eavAttributeRepository->get(
|
||||
\Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE,
|
||||
'url_key'
|
||||
);
|
||||
|
||||
// Get the default database connection.
|
||||
$connection = $this->resourceConnection->getConnection(
|
||||
\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION
|
||||
);
|
||||
|
||||
// Use a parameterized query to fetch data.
|
||||
$select = $connection->select()
|
||||
->from('catalog_product_entity_varchar')
|
||||
->where('store_id = ?', $this->storeId)
|
||||
->where('attribute_id = ?', $attribute->getId());
|
||||
|
||||
$results = $connection->fetchAll($select);
|
||||
|
||||
// Populate the storeUrlKeys array.
|
||||
foreach ($results as $result) {
|
||||
$this->storeUrlKeys[$result['value']] = $result['entity_id'];
|
||||
}
|
||||
}
|
||||
|
||||
public function productSave(\Magento\Catalog\Model\Product $product, $num = 0) {
|
||||
if ($num !== 0) {
|
||||
$oldKey = $product->getUrlKey();
|
||||
$product->setUrlKey($oldKey . '-' . $num);
|
||||
}
|
||||
|
||||
try {
|
||||
$product = $this->productRepository->save($product);
|
||||
// $saveTransaction = $this->transactionFactory->create();
|
||||
// $saveTransaction->addObject($product);
|
||||
// $saveTransaction->save();
|
||||
} catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
|
||||
|
||||
/**
|
||||
* TODO: Make this better somehow
|
||||
*
|
||||
* Dear other developers. At this point in the game I want to know if the product URL
|
||||
* key is conflicting with anything else. It's just that I want to know if the exception
|
||||
* is "AlreadyExistsException".. I also need to know if this exception
|
||||
* pertains to the URL key. What's the best way to do this?
|
||||
*
|
||||
*/
|
||||
if ($e->getMessage() == 'URL key for specified store already exists.') {
|
||||
// this means is conflicting with another URL in the catalog.. maybe CMS.. maybe Categories
|
||||
$num++;
|
||||
$product = $this->productSave($product, $num);
|
||||
} else {
|
||||
throw $e; // get caught up the stream
|
||||
}
|
||||
}
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or update a simple product, return the product
|
||||
* @param $data
|
||||
* @param $isAssociatedProduct
|
||||
* @param $configurableProductsData|null
|
||||
* @param $categoryIds|null
|
||||
* @return array
|
||||
*/
|
||||
public function createOrUpdate($data, $isAssociatedProduct, $configurableProductsData = null, $categoryIds = null) {
|
||||
if (!isset($data['sku']) || empty($data['sku'])) {
|
||||
throw new \InvalidArgumentException('Sku is Missing.');
|
||||
}
|
||||
|
||||
if (!isset($data['name']) || empty($data['name'])) {
|
||||
throw new \InvalidArgumentException('Name is Missing.');
|
||||
}
|
||||
|
||||
$product = $this->productFactory->create();
|
||||
|
||||
if ($productId = $product->getIdBySku($data['sku'])) {
|
||||
$product->load($productId);
|
||||
$product->setIsObjectNew(false);
|
||||
$updatedStock = $this->updateStockForProduct($product->getSku(), $data);
|
||||
// $this->logger->info("updated stock: " . json_encode($updatedStock));
|
||||
|
||||
if ($updatedStock['from'] != $updatedStock['to']) {
|
||||
$product = $this->productSave($product);
|
||||
$this->logger->info("save product stock, sku: " . $product->getSku() . " " . json_encode($updatedStock));
|
||||
}
|
||||
|
||||
if ($product->getPrice() != $data['price']) {
|
||||
$product->setPrice($data['price']);
|
||||
$product = $this->productSave($product);
|
||||
$this->logger->info("save product price, sku: " . $product->getSku());
|
||||
}
|
||||
|
||||
if (($product->getCustomAttribute('netsuite_id')?->getValue() ?? "") != $data['netsuite_product_id']) {
|
||||
$product->setCustomAttribute('netsuite_id', $data['netsuite_product_id']);
|
||||
$product = $this->productSave($product);
|
||||
$this->logger->info("save product netsuite_id, sku: " . $product->getSku());
|
||||
}
|
||||
|
||||
return [
|
||||
'data' => $product,
|
||||
'is_new' => false
|
||||
];
|
||||
} else {
|
||||
$product->setIsObjectNew(true);
|
||||
}
|
||||
|
||||
//general stuff
|
||||
$product->setStoreId($this->storeId)
|
||||
->setAttributeSetId(4)
|
||||
->setWebsiteIds([1])
|
||||
// ->setStatus($data['status'] && $data['custitem_item_eol_for_sales'] ? ProductStatus::STATUS_ENABLED : ProductStatus::STATUS_DISABLED);
|
||||
->setStatus(ProductStatus::STATUS_DISABLED);
|
||||
|
||||
//actual data from our json
|
||||
$product->setName($data['name'])
|
||||
->setSku($data['sku'])
|
||||
// ->setShortDescription($data['shortDescription'])
|
||||
->setDescription($data['description'])
|
||||
->setPrice($data['price'])
|
||||
->setWeight($data['weight']);
|
||||
|
||||
$product->setCustomAttribute('netsuite_id', $data['netsuite_product_id']);
|
||||
|
||||
if (isset($data['priceSpecial'])) {
|
||||
$product->setSpecialPrice($data['priceSpecial']);
|
||||
}
|
||||
|
||||
$product = $this->setVisibility($product, $isAssociatedProduct);
|
||||
$product = $this->setTaxClassId($product);
|
||||
|
||||
if ($categoryIds && is_array($categoryIds)) {
|
||||
$product->setCategoryIds($categoryIds);
|
||||
}
|
||||
|
||||
$product = $this->setUrlKey($product);
|
||||
|
||||
if ((!$configurableProductsData || count($configurableProductsData) == 0)) {
|
||||
$product->setTypeId(ProductType::TYPE_SIMPLE);
|
||||
$product = $this->productSave($product);
|
||||
|
||||
$this->updateStockForProduct($product->getSku(), $data);
|
||||
|
||||
return [
|
||||
'data' => $product,
|
||||
'is_new' => true
|
||||
];
|
||||
}
|
||||
|
||||
// CONFIGURABLE PRODUCT !!!!
|
||||
|
||||
$product->setTypeId(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);
|
||||
$product->setStockData(['use_config_manage_stock' => 1, 'is_in_stock' => 1]);
|
||||
|
||||
$product = $this->attributesSync->attachAttributesFromChildData($product, $configurableProductsData);
|
||||
$product = $this->productSave($product);
|
||||
|
||||
if ($product->getIsObjectNew() == false) {
|
||||
$this->removeOldAssociatedProducts($product, array_keys($configurableProductsData));
|
||||
}
|
||||
|
||||
// so we can check this later since the list of keys is cached.
|
||||
$this->storeUrlKeys[$product->getUrlKey()] = $product->getId();
|
||||
|
||||
return [
|
||||
'data' => $product,
|
||||
'is_new' => true
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Magento\Catalog\Model\Product $product
|
||||
* @param array $correctChildIds
|
||||
*/
|
||||
private function removeOldAssociatedProducts(\Magento\Catalog\Model\Product $product, $correctChildIds) {
|
||||
$children = $product->getTypeInstance()->getUsedProducts($product);
|
||||
|
||||
foreach ($children as $child) {
|
||||
if (in_array($child->getId(), $correctChildIds)) {
|
||||
continue; // cool. no need to do anything.. we like this product.
|
||||
}
|
||||
$this->registry->register('isSecureArea', true);
|
||||
$this->productRepository->delete($child);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Magento\Catalog\Model\Product $product
|
||||
* @return \Magento\Catalog\Model\Product
|
||||
*/
|
||||
private function setUrlKey(\Magento\Catalog\Model\Product $product) {
|
||||
$key = $product->formatUrlKey($product->getSku());
|
||||
|
||||
if (!isset($this->storeUrlKeys[$key])) {
|
||||
return $product; // no conflict
|
||||
}
|
||||
|
||||
if ($this->storeUrlKeys[$key] == $product->getId()) {
|
||||
return $product; // no conflict we're updated the product
|
||||
}
|
||||
|
||||
$newKey = $product->formatUrlKey($product->getSku()) . '-1';
|
||||
$product->setUrlKey($newKey);
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Magento\Catalog\Model\Product $product
|
||||
* @return \Magento\Catalog\Model\Product
|
||||
*/
|
||||
private function setTaxClassId(\Magento\Catalog\Model\Product $product) {
|
||||
if ($product->getIsObjectNew() == true) {
|
||||
$product->setTaxClassId($this->defaultTaxClass);
|
||||
}
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Magento\Catalog\Model\Product $product
|
||||
* @param bool $isAssociatedProduct
|
||||
* @return \Magento\Catalog\Model\Product
|
||||
*/
|
||||
private function setVisibility(\Magento\Catalog\Model\Product $product, $isAssociatedProduct) {
|
||||
if ($isAssociatedProduct) {
|
||||
$product->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE);
|
||||
return $product;
|
||||
}
|
||||
|
||||
if ($product->getIsObjectNew() == true) {
|
||||
$product->setVisibility($this->visibility);
|
||||
return $product;
|
||||
}
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
/**
|
||||
* get source code by location id
|
||||
* @param $locationId
|
||||
* @return string
|
||||
*/
|
||||
public function getSourceCodeByLocationId($locationId) {
|
||||
$locationCollection = $this->locationCollectionFactory->create();
|
||||
$locationCollection->addFieldToFilter('netsuite_id', $locationId)
|
||||
->addFieldToFilter('is_active', 1);
|
||||
$location = $locationCollection->getFirstItem();
|
||||
$result = $location->getData();
|
||||
return $result['source_code'] ?? 'default';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $productSku
|
||||
* @param float $qty
|
||||
* @param string $scopeId
|
||||
* @return array
|
||||
*/
|
||||
public function updateStockForProduct(string $productSku, $data, $scopeId = 0): array {
|
||||
$stockId = $this->getStockIdForCurrentWebsite->execute();
|
||||
$qty = $data['qty'] ?? 0;
|
||||
// $this->logger->info($productSku . " qty: " . $qty);
|
||||
//$this->logger->info("XXXY quantity = " . $qty . ", SKU = " . $productSku . ", data = " . json_encode($data));
|
||||
if (empty($data['locationId'])) {
|
||||
$this->logger->info("XXXY empty locationID, " . json_encode($data));
|
||||
$qty -= $this->getReservationsQuantity->execute($productSku, $stockId);
|
||||
}
|
||||
// $this->logger->info($productSku . " qty: " . $qty);
|
||||
|
||||
if ($this->helper->getMultiLocationEnabled()) {
|
||||
$sourceCode = $this->getSourceCodeByLocationId($data['locationId'] ?? '');
|
||||
} else {
|
||||
$this->logger->info("XXXY can't find source by locationID, " . json_encode($data));
|
||||
$sourceCode = 'default';
|
||||
}
|
||||
|
||||
//$this->logger->info("XXXY Source code: " . $sourceCode);
|
||||
|
||||
// Check if SourceItem already exists for given SKU and Source.
|
||||
$sourceItems = $this->getSourceItemsBySku->execute($productSku);
|
||||
$existingSourceItem = array_filter($sourceItems, function ($item) use ($sourceCode) {
|
||||
return $item->getSourceCode() === $sourceCode;
|
||||
});
|
||||
|
||||
$sourceItem = $existingSourceItem ? reset($existingSourceItem) : $this->sourceItemFactory->create();
|
||||
|
||||
$originQty = null;
|
||||
if (!$existingSourceItem) {
|
||||
$sourceItem->setSourceCode($sourceCode);
|
||||
$sourceItem->setSku($productSku);
|
||||
} else {
|
||||
$originQty = $sourceItem->getQuantity();
|
||||
}
|
||||
|
||||
$sourceItem->setQuantity($qty);
|
||||
$sourceItem->setStatus($qty > 0 ? SourceItemInterface::STATUS_IN_STOCK : SourceItemInterface::STATUS_OUT_OF_STOCK);
|
||||
/*
|
||||
$this->logger->info("XXXY SourceItem before save", [
|
||||
'SKU' => $sourceItem->getSku(),
|
||||
'Source Code' => $sourceItem->getSourceCode(),
|
||||
'Quantity' => $sourceItem->getQuantity(),
|
||||
'Status' => $sourceItem->getStatus()
|
||||
]);
|
||||
*/
|
||||
$this->sourceItemsSave->execute([$sourceItem]);
|
||||
|
||||
return [
|
||||
'sku' => $productSku,
|
||||
'from' => $originQty,
|
||||
'to' => $qty,
|
||||
'location' => $sourceCode ?? 'default'
|
||||
];
|
||||
}
|
||||
|
||||
private function setStockData(\Magento\Catalog\Model\Product $product, $qty) {
|
||||
$product->setQuantityAndStockStatus(['qty' => $qty, 'is_in_stock' => 1])
|
||||
->setStockData([
|
||||
'use_config_manage_stock' => 0,
|
||||
//'Use config settings' checkbox
|
||||
'manage_stock' => 1,
|
||||
//manage stock
|
||||
'is_in_stock' => $qty > 0,
|
||||
//Stock Availability
|
||||
'qty' => $qty
|
||||
]);
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+421
@@ -0,0 +1,421 @@
|
||||
<?php
|
||||
namespace JR\NetSuite\Service;
|
||||
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\User\Model\User;
|
||||
use Magento\User\Model\ResourceModel\User\CollectionFactory as UserCollectionFactory;
|
||||
use Mirasvit\Rma\Model\ResourceModel\Address\CollectionFactory as AddressCollectionFactory;
|
||||
use Mirasvit\Rma\Model\ResourceModel\Rma\CollectionFactory as RmaCollectionFactory;
|
||||
use Mirasvit\Rma\Model\ResourceModel\Condition\CollectionFactory as ConditionCollectionFactory;
|
||||
use Mirasvit\Rma\Model\ResourceModel\Reason\CollectionFactory as ReasonCollectionFactory;
|
||||
use Mirasvit\Rma\Model\ResourceModel\Resolution\CollectionFactory as ResolutionCollectionFactory;
|
||||
use Mirasvit\Rma\Model\AddressFactory;
|
||||
use Mirasvit\Rma\Api\Repository\AddressRepositoryInterface;
|
||||
use \Mirasvit\Rma\Api\Repository\RmaRepositoryInterface;
|
||||
use Mirasvit\Rma\Api\Repository\StatusRepositoryInterface;
|
||||
use \Mirasvit\Rma\Api\Service\Rma\RmaManagementInterface;
|
||||
use Mirasvit\Rma\Controller\Adminhtml\Rma\Save as RmaSave;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\Message\ManagerInterface;
|
||||
use \Mirasvit\Rma\Api\Service\Performer\PerformerFactoryInterface;
|
||||
use Mirasvit\Rma\Api\Service\Rma\RmaManagement\SaveInterface;
|
||||
use \Mirasvit\Rma\Controller\Adminhtml\Rma\PostDataProcessor;
|
||||
|
||||
use JR\NetSuite\Model\ResourceModel\Location\CollectionFactory as LocationCollectionFactory;
|
||||
use JR\NetSuite\Mapper\RmaMapper;
|
||||
use JR\NetSuite\Mapper\orderMapper;
|
||||
use JR\NetSuite\Logger\Logger;
|
||||
|
||||
class RmaSyncService
|
||||
{
|
||||
const TAX_GROUP = 'TaxGroup';
|
||||
const SHIP_ITEM = 'ShipItem';
|
||||
const INVT_PART = 'InvtPart';
|
||||
const DISCOUNT = 'Discount';
|
||||
|
||||
const REASON_MAP = [
|
||||
'3' => 'S-Internal Error', // sales made mistake
|
||||
'4' => 'DOA',
|
||||
'5' => 'Customer Cancellation',
|
||||
'6' => 'Manufacture Defect',
|
||||
];
|
||||
|
||||
const CONDITION_MAP = [
|
||||
'2' => 'Wrong Merchandise Received',
|
||||
'6' => 'Product Defective',
|
||||
'11' => 'No Longer Needed/Return as New',
|
||||
'13' => 'Others',
|
||||
];
|
||||
|
||||
const RESOLUTION_MAP = [
|
||||
'1' => 'AR with Return',
|
||||
'2' => 'Replacement',
|
||||
'3' => 'Refund',
|
||||
'4' => 'Credit',
|
||||
'5' => 'AR without Return',
|
||||
'6' => 'Substitute',
|
||||
];
|
||||
|
||||
/**
|
||||
* @var RmaCollectionFactory
|
||||
*/
|
||||
protected $rmaCollectionFactory;
|
||||
|
||||
/**
|
||||
* @var RmaRepositoryInterface
|
||||
*/
|
||||
protected $rmaRepository;
|
||||
|
||||
/**
|
||||
* @var StatusRepositoryInterface
|
||||
*/
|
||||
protected $statusRepository;
|
||||
|
||||
/**
|
||||
* @var RmaManagementInterface
|
||||
*/
|
||||
protected $rmaManagement;
|
||||
|
||||
/**
|
||||
* @var RmaSave
|
||||
*/
|
||||
protected $rmaSave;
|
||||
|
||||
/**
|
||||
* @var RequestInterface
|
||||
*/
|
||||
protected $request;
|
||||
|
||||
/**
|
||||
* @var ManagerInterface
|
||||
*/
|
||||
protected $messageManager;
|
||||
|
||||
/**
|
||||
* @var PerformerFactoryInterface
|
||||
*/
|
||||
private $performer;
|
||||
|
||||
/**
|
||||
* @var SaveInterface
|
||||
*/
|
||||
private $rmaSaveService;
|
||||
|
||||
/**
|
||||
* @var PostDataProcessor
|
||||
*/
|
||||
private $dataProcessor;
|
||||
|
||||
/**
|
||||
* @var UserCollectionFactory
|
||||
*/
|
||||
protected $userCollectionFactory;
|
||||
|
||||
/**
|
||||
* @var RmaMapper
|
||||
*/
|
||||
protected $rmaMapper;
|
||||
|
||||
/**
|
||||
* @var OrderMapper
|
||||
*/
|
||||
protected $orderMapper;
|
||||
|
||||
/**
|
||||
* @var Logger
|
||||
*/
|
||||
protected $logger;
|
||||
|
||||
/**
|
||||
* @var \Mirasvit\Rma\Model\ResourceModel\Condition\CollectionFactory
|
||||
*/
|
||||
private $conditionCollectionFactory;
|
||||
|
||||
/**
|
||||
* @var \Mirasvit\Rma\Model\ResourceModel\Reason\CollectionFactory
|
||||
*/
|
||||
private $ReasonCollectionFactory;
|
||||
|
||||
/**
|
||||
* @var \Mirasvit\Rma\Model\ResourceModel\Resolution\CollectionFactory
|
||||
*/
|
||||
private $resolutionCollectionFactory;
|
||||
|
||||
/**
|
||||
* @var \JR\NetSuite\Model\ResourceModel\Location\CollectionFactory
|
||||
*/
|
||||
private $locationCollectionFactory;
|
||||
|
||||
/**
|
||||
* @var \Mirasvit\Rma\Model\ResourceModel\Address\CollectinFatory
|
||||
*/
|
||||
private $AddressCollectionFactory;
|
||||
|
||||
/**
|
||||
* @var \Mirasvit\Rma\Model\AddressFactory
|
||||
*/
|
||||
private $addressFactory;
|
||||
|
||||
/**
|
||||
* @var \Mirasvit\Rma\Api\Repository\AddressRepositoryInterface
|
||||
*/
|
||||
private $addressRepository;
|
||||
|
||||
/**
|
||||
* @var \Magento\Customer\Api\CustomerRepositoryInterface
|
||||
*/
|
||||
private $customerRepository;
|
||||
|
||||
/**
|
||||
* @var \Magento\Framework\Registry
|
||||
*/
|
||||
private $registry;
|
||||
|
||||
public function __construct(
|
||||
RmaCollectionFactory $rmaCollectionFactory,
|
||||
RmaRepositoryInterface $rmaRepository,
|
||||
StatusRepositoryInterface $statusRepository,
|
||||
RmaManagementInterface $rmaManagement,
|
||||
RmaSave $rmaSave,
|
||||
RequestInterface $request,
|
||||
ManagerInterface $messageManager,
|
||||
PerformerFactoryInterface $performer,
|
||||
SaveInterface $rmaSaveService,
|
||||
PostDataProcessor $dataProcessor,
|
||||
UserCollectionFactory $userCollectionFactory,
|
||||
ConditionCollectionFactory $conditionCollectionFactory,
|
||||
ReasonCollectionFactory $ReasonCollectionFactory,
|
||||
ResolutionCollectionFactory $resolutionCollectionFactory,
|
||||
RmaMapper $rmaMapper,
|
||||
OrderMapper $orderMapper,
|
||||
LocationCollectionFactory $locationCollectionFactory,
|
||||
AddressCollectionFactory $AddressCollectionFactory,
|
||||
AddressFactory $addressFactory,
|
||||
AddressRepositoryInterface $addressRepository,
|
||||
Logger $logger,
|
||||
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
|
||||
\Magento\Framework\Registry $registry
|
||||
) {
|
||||
$this->rmaCollectionFactory = $rmaCollectionFactory;
|
||||
$this->rmaRepository = $rmaRepository;
|
||||
$this->statusRepository = $statusRepository;
|
||||
$this->rmaManagement = $rmaManagement;
|
||||
$this->rmaSave = $rmaSave;
|
||||
$this->request = $request;
|
||||
$this->messageManager = $messageManager;
|
||||
$this->performer = $performer;
|
||||
$this->rmaSaveService = $rmaSaveService;
|
||||
$this->dataProcessor = $dataProcessor;
|
||||
$this->userCollectionFactory = $userCollectionFactory;
|
||||
$this->rmaMapper = $rmaMapper;
|
||||
$this->orderMapper = $orderMapper;
|
||||
$this->logger = $logger;
|
||||
$this->customerRepository = $customerRepository;
|
||||
$this->registry = $registry;
|
||||
$this->addressRepository = $addressRepository;
|
||||
$this->addressFactory = $addressFactory;
|
||||
$this->AddressCollectionFactory = $AddressCollectionFactory;
|
||||
$this->locationCollectionFactory = $locationCollectionFactory;
|
||||
$this->resolutionCollectionFactory = $resolutionCollectionFactory;
|
||||
$this->ReasonCollectionFactory = $ReasonCollectionFactory;
|
||||
$this->conditionCollectionFactory = $conditionCollectionFactory;
|
||||
}
|
||||
|
||||
public function updateRmaStatus($data) {
|
||||
if (empty($data)) {
|
||||
return;
|
||||
}
|
||||
// update RMA status
|
||||
$rmas = $this->rmaCollectionFactory->create();
|
||||
$rmas->addFieldToFilter('rma_id', array('in' => array_keys($data)));
|
||||
foreach ($rmas as $rma) {
|
||||
$code = strtolower($data[$rma->getRmaId()]);
|
||||
$status = $this->statusRepository->getByCode($code);
|
||||
if (!$status?->getId()) {
|
||||
continue;
|
||||
}
|
||||
$rma->setStatusId($status->getId());
|
||||
$rma->save();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function createInNetSuite($rmaId) {
|
||||
$rma = $this->rmaRepository->get($rmaId);
|
||||
$order = $this->rmaManagement->getOrder($rma);
|
||||
$customer = $this->rmaManagement->getCustomer($rma);
|
||||
$rmaData = $this->rmaMapper->convertToNetSuiteFormat($rma, $order, $customer);
|
||||
}
|
||||
|
||||
public function getOrder($data) {
|
||||
if (empty($data['netsuite_order_id']) && empty($data['netsuite_order_number'])) {
|
||||
throw new \Exception('Skipped: Netsuite order not found.');
|
||||
}
|
||||
|
||||
if (!empty($data['netsuite_order_id'])) {
|
||||
$order = $this->orderMapper->getOrderBy('netsuite_id', $data['netsuite_order_id']);
|
||||
}
|
||||
|
||||
if (!isset($order) && !empty($data['netsuite_order_number'])) {
|
||||
$netsuiteNumber = 'SO' . str_pad(ltrim($data['netsuite_order_number'], '#SOso0'), 7, '0', STR_PAD_LEFT);
|
||||
$order = $this->orderMapper->getOrderBy('netsuite_number', $netsuiteNumber);
|
||||
}
|
||||
|
||||
if (!$order) {
|
||||
throw new \Exception('Skipped: Netsuite order not sync.');
|
||||
}
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
public function createOrSkip($data, $order = null) {
|
||||
// if (!isset($data['customer']['email']) || empty($data['customer']['email'])) {
|
||||
// throw new \Exception('Skipped: Customer email not found.');
|
||||
// }
|
||||
|
||||
// // found customer id by email
|
||||
// $customer = $this->customerRepository->get($data['customer']['email']);
|
||||
// if (!$customer) {
|
||||
// // retrun error
|
||||
// throw new \Exception('Skipped: Customer not found.');
|
||||
// }
|
||||
|
||||
if (!$order) $order = $this->getOrder($data);
|
||||
|
||||
// if ($order->getCustomerEmail() != $data['customer']['email']) {
|
||||
// throw new \Exception('Skipped: Customer email not match.');
|
||||
// }
|
||||
|
||||
// if billing zipcode not match
|
||||
// if (isset($data['customer']['billing_address']['postcode']) && $order->getBillingAddress()->getPostcode() != $data['customer']['billing_address']['postcode']) {
|
||||
// throw new \Exception('Skipped: Billing zipcode not match.');
|
||||
// }
|
||||
|
||||
// get all condition and reason
|
||||
$conditions = $this->conditionCollectionFactory->create();
|
||||
$reasons = $this->ReasonCollectionFactory->create();
|
||||
$resolution = $this->resolutionCollectionFactory->create();
|
||||
$conditionMap = [];
|
||||
$reasonMap = [];
|
||||
$resolutionMap = [];
|
||||
foreach ($conditions as $condition) {
|
||||
$conditionMap[$condition->getName()] = $condition->getId();
|
||||
}
|
||||
foreach ($reasons as $reason) {
|
||||
$reasonMap[$reason->getName()] = $reason->getId();
|
||||
}
|
||||
foreach ($resolution as $res) {
|
||||
$resolutionMap[$res->getName()] = $res->getId();
|
||||
}
|
||||
|
||||
// get all order items
|
||||
$orderItems = $order->getAllItems();
|
||||
$filteredOrderItems = [];
|
||||
$skuMap = array_column($data['items'], 'sku');
|
||||
foreach ($orderItems as $orderItem) {
|
||||
if (in_array($orderItem->getSku(), $skuMap)) {
|
||||
$filteredOrderItems[$orderItem->getSku()] = $orderItem->getId();
|
||||
}
|
||||
}
|
||||
|
||||
$items = [];
|
||||
foreach ($data['items'] as $item) {
|
||||
if ($item['type'] != self::INVT_PART) {
|
||||
continue;
|
||||
}
|
||||
$items[] = [
|
||||
'order_id' => $order->getId(),
|
||||
'order_item_id' => $filteredOrderItems[$item['sku']],
|
||||
'product_sku' => $item['sku'],
|
||||
'qty_requested' => abs($item['qty']),
|
||||
'reason_id' => $item['reason'] != '' ? $reasonMap[self::REASON_MAP[$item['reason']]] : '',
|
||||
'condition_id' => $item['condition'] != '' ? $conditionMap[self::CONDITION_MAP[$item['condition']]] : '',
|
||||
'resolution_id' => $item['resolution'] != '' ? $resolutionMap[self::RESOLUTION_MAP[$item['resolution']]] : '',
|
||||
];
|
||||
}
|
||||
|
||||
$status = $this->statusRepository->getByCode($data['status']);
|
||||
|
||||
// filter location by loction id and get the name
|
||||
$location = $this->locationCollectionFactory->create()->addFieldToFilter('location_id', $data['location'])->getFirstItem();
|
||||
|
||||
if (!$location) {
|
||||
throw new \Exception('Skipped: Location not found.');
|
||||
}
|
||||
|
||||
// find the return address
|
||||
$address = $this->AddressCollectionFactory->create()->addFieldToFilter('name', $location->getName())->getFirstItem();
|
||||
if (!$address) {
|
||||
// add the address to the address table by get the repository
|
||||
$address = $this->addressFactory->create();
|
||||
$address->addData([
|
||||
'is_active' => 1,
|
||||
'address' => $location->getAddress(),
|
||||
'name' => $location->getName(),
|
||||
]);
|
||||
$address = $this->addressRepository->save($address);
|
||||
}
|
||||
|
||||
$params = [
|
||||
'order_id' => $order->getId(),
|
||||
'user_id' => 0,
|
||||
'status_id' => $status->getId(),
|
||||
'is_resolved' => in_array($data['status'], ['refunded', 'closed', 'cancelled']),
|
||||
'return_address' => $address->getId(),
|
||||
'first_name' => $data['customer']['firstname'],
|
||||
'last_name' => $data['customer']['lastname'],
|
||||
'company' => $data['customer']['company_name'],
|
||||
'email' => $order->getCustomerEmail(),
|
||||
'phone' => $data['customer']['shipping_address']['telephone'],
|
||||
'street' => $data['customer']['shipping_address']['street'][0],
|
||||
'street2' => $data['customer']['shipping_address']['street'][1],
|
||||
'city' => $data['customer']['shipping_address']['city'],
|
||||
'postcode' => $data['customer']['shipping_address']['postcode'],
|
||||
'items' => $items,
|
||||
];
|
||||
|
||||
// unset current_rma registry
|
||||
$this->registry->unregister('current_rma');
|
||||
$user = $this->userCollectionFactory->create()->getFirstItem();
|
||||
$performer = $this->performer->create(PerformerFactoryInterface::USER, $user);
|
||||
$rma = $this->rmaSaveService->saveRma(
|
||||
$performer,
|
||||
$this->dataProcessor->filterRmaData($params),
|
||||
$this->dataProcessor->filterRmaItems($params)
|
||||
);
|
||||
|
||||
// save created at time to rma
|
||||
$createdAt = \DateTime::createFromFormat('m/d/Y g:i a', $data['recorded_at'], new \DateTimeZone('America/Los_Angeles'));
|
||||
$createdAt->setTimezone(new \DateTimeZone('UTC'));
|
||||
$rma->setCreatedAt($createdAt->format('Y-m-d H:i:s'));
|
||||
$rma->save();
|
||||
|
||||
return [
|
||||
'data' => $rma,
|
||||
'is_new' => true
|
||||
];
|
||||
|
||||
}
|
||||
|
||||
public function update($data, $rmaId) {
|
||||
if (empty($data['status'])) {
|
||||
throw new \Exception('Skipped: Status not found.');
|
||||
}
|
||||
|
||||
$rma = $this->rmaRepository->get($rmaId);
|
||||
|
||||
$status = $this->statusRepository->getByCode($data['status']);
|
||||
if (!$status) {
|
||||
throw new \Exception('Skipped: Status not found.');
|
||||
}
|
||||
|
||||
$rma->setStatusId($status->getId());
|
||||
$rma->save();
|
||||
|
||||
return [
|
||||
'data' => $rma,
|
||||
'is_new' => false
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user