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
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace JR\NetSuite\Mapper;
use JR\NetSuite\Model\Data\ProductQueueItem;
// the common mapping logic that can be used for any entity type
abstract class AbstractMapper
{
/**
* @var ProductQueueItem
*/
protected $queueItem;
/**
* @param ProductQueueItem $queueItem
*/
public function __construct(
ProductQueueItem $queueItem
) {
$this->queueItem = $queueItem;
}
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
abstract public function convertToMagentoFormat($netSuiteData);
/**
* Convert data from Magento format to NetSuite format.
*
* @param array $magentoData
* @return array
*/
abstract public function convertToNetSuiteFormat($magentoData);
}
+490
View File
@@ -0,0 +1,490 @@
<?php
namespace JR\NetSuite\Mapper;
use JR\NetSuite\Mapper\AbstractMapper;
use Magento\Directory\Model\RegionFactory;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Api\Data\AddressInterfaceFactory;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Framework\Event\ManagerInterface as EventManager;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Directory\Model\CountryFactory;
// Handles the specifics of mapping product data.
class CustomerMapper {
const STATUSES = [
'13' => 'Customer-Active',
'21' => 'Customer-Bad Debt',
'20' => 'Customer-Blacklist',
'22' => 'Customer-Fraudulent',
'15' => 'Customer-Inactive',
'23' => 'Customer-New',
'17' => 'Lead-Free',
'6' => 'Lead-New',
'18' => 'Lead-Pending Approval',
'7' => 'Lead-Unqualified',
'8' => 'Prospect-In Discussion',
'10' => 'Prospect-Proposal',
];
/**
* customer group
*
* @var string
*/
protected $default_customer_group;
/**
* helper
*
* @var \JR\NetSuite\Helper\Data
*/
protected $helper;
/**
* array to store customer group id.
*
* @var int
*/
protected $customerGroupIdMap = [];
/**
* @var RegionFactory
*/
protected $regionFactory;
/**
* @var \Magento\Customer\Model\GroupFactory
*/
protected $customerGroupFactory;
/**
* @var GroupRepositoryInterface
*/
protected $groupRepository;
/**
* @var SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;
/**
* @var CustomerRepositoryInterface
*/
protected $customerRepository;
/**
* @var CustomerInterfaceFactory
*/
protected $customerFactory;
/**
* @var AddressInterfaceFactory
*/
protected $addressFactory;
/**
* @var EventManager
*/
protected $eventManager;
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var CountryFactory
*/
protected $countryFactory;
/**
* CustomerMapper constructor.
*/
public function __construct(
RegionFactory $regionFactory,
\Magento\Customer\Model\GroupFactory $customerGroupFactory,
GroupRepositoryInterface $groupRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
\JR\NetSuite\Helper\Data $helper,
CustomerRepositoryInterface $customerRepository,
CustomerInterfaceFactory $customerFactory,
AddressInterfaceFactory $addressFactory,
EventManager $eventManager,
StoreManagerInterface $storeManager,
CountryFactory $countryFactory
) {
$this->regionFactory = $regionFactory;
$this->customerGroupFactory = $customerGroupFactory;
$this->groupRepository = $groupRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->helper = $helper;
$this->default_customer_group = $this->helper->getDefaultCustomerGroup();
$this->customerRepository = $customerRepository;
$this->customerFactory = $customerFactory;
$this->addressFactory = $addressFactory;
$this->eventManager = $eventManager;
$this->storeManager = $storeManager;
$this->countryFactory = $countryFactory;
}
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
public function convertToMagentoFormat($netSuiteData) {
/*
[internalid] => 246911
[isinactive] =>
[entityid] => 08/03NJ-MET-NC
[entitystatus] => 8
[addressee] => Modern Edge Technologies
[addressphone] => (336) 699-2158
[email] => babbott@modernedgetechnology.com
[phone] => (336) 699-2158
[balance] => .00
[creditlimit] => 1.00
[billattention] => Black Abbott
[billaddress1] => 6629 Old U.S. 421
[billaddress2] =>
[billaddressee] => Modern Edge Technologies
[billcity] => East Bend
[billcountry] => US
[billstate] => NC
[billzipcode] => 27018
[isdefaultbilling] => 1
[isperson] =>
[firstname] =>
[lastname] =>
[companyname] => Modern Edge Technologies
[shipaddress1] => 6629 Old U.S. 421
[shipaddress2] =>
[shipaddressee] => Modern Edge Technologies
[shipattention] => Black Abbott
[shipcity] => East Bend
[shipcomplete] =>
[shipcountry] => US
[shippingcarrier] =>
[shipstate] => NC
[shipzip] => 27018
[isdefaultshipping] => 1
*/
// echo json_encode($netSuiteData, JSON_PRETTY_PRINT) . "\n";
// convert netsuite data to magento data
$magentoData = [];
foreach ($netSuiteData as $data) {
$name = $this->filterFirstNonEmpty([
$data['shipattention'] ?? '',
$data['billattention'] ?? '',
$data['addressee'] ?? '',
$data['companyname'],
]);
$convertedData = [
'is_active' => $data['isinactive'] ? 0 : 1,
'netsuite_entity_id' => $data['entityid'],
'netsuite_customer_id' => $data['internalid'],
'status' => self::STATUSES[$data['entitystatus']],
'firstname' => count($name) > 0 ? array_shift($name) : $this->replaceName($data['companyname']),
'lastname' => count($name) > 0 ? (empty(implode(' ', $name)) ? $this->replaceName($data['companyname']) : implode(' ', $name)) : $this->replaceName($data['companyname']),
'email' => $data['email'],
'company_name' => $data['companyname'],
'phone' => $data['phone'],
'group_id' => $this->getDefaultCustomerGroupId(),
'reporting_office' => $data['cseg_ncg_rep_office'],
'isdefaultshipping' => $data['isdefaultshipping'],
'isdefaultbilling' => $data['isdefaultbilling'],
];
$shipaddressee = $this->filterFirstNonEmpty([
$data['shipattention'],
$data['shipaddressee'],
$data['billattention'] ?? '',
]);
if (empty($shipaddressee)) {
$shipaddressee = $this->getNameFromAddressText($data['shipaddress']);
}
$convertedData['shipping_address'] = [
'firstname' => count($shipaddressee) > 0 ? array_shift($shipaddressee) : '',
'lastname' => count($shipaddressee) > 0 ? implode(' ', $shipaddressee) : $data['companyname'],
'company' => $data['companyname'],
'street' => $data['shipaddress1'] != '' ?
[$data['shipaddress1'], $data['shipaddress2']] :
[$data['billaddress1'], $data['billaddress2']],
'city' => $data['shipcity'],
'country_id' => $data['shipcountry'],
// 'region' => $data['shipstate'],
'region_id' => $this->getRegion($data['shipcountry'], $data['shipstate'])->getId(),
'postcode' => $data['shipzip'],
'telephone' => $data['addressphone'] == '' ? $data['phone'] : $data['addressphone'],
];
$billaddressee = $this->filterFirstNonEmpty([
$data['billattention'],
$data['billaddressee'],
$data['shipattention'] ?? '',
]);
if (empty($billaddressee)) {
$billaddressee = $this->getNameFromAddressText($data['billaddress']);
}
$convertedData['billing_address'] = [
'firstname' => count($billaddressee) > 0 ? array_shift($billaddressee) : '',
'lastname' => count($billaddressee) > 0 ?
(empty(implode(' ', $billaddressee)) ? $data['companyname'] : implode(' ', $billaddressee)) : $data['companyname'],
'company' => $data['companyname'],
'street' => [$data['billaddress1'], $data['billaddress2']],
'city' => $data['billcity'],
'country_id' => $data['billcountry'],
// 'region' => $data['billstate'],
'region_id' => $this->getRegion($data['billcountry'], $data['billstate'])->getId(),
'postcode' => $data['billzipcode'],
'telephone' => $data['addressphone'] == '' ? $data['phone'] : $data['addressphone'],
];
// 'phone' => $data['phone'],
// 'fax' => $data['fax'],
// 'website' => $data['url'],
// 'street' => $data['address1'],
// 'city' => $data['city'],
// 'country_id' => $data['country'],
// 'region' => $data['state'],
// 'postcode' => $data['zip'],
// 'created_at' => $data['createddate'],
// 'updated_at' => $data['lastmodifieddate']
$magentoData[] = $convertedData;
}
return $magentoData;
}
/**
* Convert data from Magento format to NetSuite format.
*
* @param array $magentoData
* @return array
*/
public function convertToNetSuiteFormat($magentoData) {
// Your conversion logic here
}
/**
* convert magento customer to netsuite format by email
*/
public function convertToNetSuiteFormatByEmail($email) {
$customer = $this->customerRepository->get($email);
$phone = $customer->getCustomAttribute('phone')?->getValue();
$company = $customer->getCustomAttribute('company')?->getValue();
$defaultBillingAddressId = $customer->getDefaultBilling() ?? null;
$defaultShippingAddressId = $customer->getDefaultShipping() ?? null;
$netsuiteAddressList = [];
$addresses = $customer->getAddresses();
foreach ($addresses as $address) {
$netsuiteAddress = new \stdClass(); // Assuming stdClass for simplicity, replace with actual class if applicable
$netsuiteAddress->attention = $customer->getFirstname() . ' ' . $customer->getLastname();
$street = array_filter($address->getStreet());
if (count($street) == 1) {
$street = explode(",", $street[0]);
if (count($street) > 2) {
$street1 = trim(implode(",", array_slice($street, 0, count($street) - 1)));
} else {
$street1 = trim($street[0]);
}
if (count($street) > 1) {
$street2 = trim($street[count($street) - 1]);
}
}
$netsuiteAddress->addr1 = $street1 ?? '';
$netsuiteAddress->addr2 = $street2 ?? '';
$netsuiteAddress->city = $address->getCity() ?? '';
$netsuiteAddress->zip = $address->getPostcode() ?? '';
$netsuiteAddress->state = $address->getRegion()?->getRegionCode() ?? '';
$netsuiteAddress->country = $address->getCountryId() ?? '';
$phone = $phone ?? $address->getTelephone();
$company = $company ?? $address->getCompany();
// Dispatch event or additional processing
// $this->eventManager->dispatch('netsuite_address_create_before', ['netsuite_address' => $netsuiteAddress]);
$netsuiteAddressList[] = [
'defaultbilling' => $address->getId() == $defaultBillingAddressId,
'defaultshipping' => $address->getId() == $defaultShippingAddressId,
'address' => $netsuiteAddress,
];
}
if (!empty($phone)) {
$phone = preg_replace('/[^0-9]/', '', $phone);
if (strlen($phone) == 10) {
$phone = '0001' . $phone;
}
$phone = str_pad($phone, 14, '0', STR_PAD_LEFT);
}
$netsuiteCustomer = [
//"requestTime": 40780772495802300,
'requestTime' => time(),
'firstName' => $customer->getFirstname(),
'lastName' => $customer->getLastname(),
'addressBooks' => $netsuiteAddressList,
'isPerson' => "T",
'phone' => $phone ?? '',
'companyname' => $company ?? '',
'custentity_source' => 3,
'entityid' => 'magento_' . $customer->getId(),
'leadsource' => -6,
'title' => $customer->getPrefix() ?? '',
'email' => $customer->getEmail(),
];
return $netsuiteCustomer;
}
/**
* Convert data to NetSuite format by order
*
* @param OrderInterface $order
* @return array
*/
public function convertToNetSuiteFormatByOrder(OrderInterface $order) {
if ($customerData = $this->convertToNetSuiteFormatByEmail($order->getCustomerEmail())) {
return $customerData;
}
$customer = $this->customerFactory->create();
$customer->setEmail($order->getCustomerEmail())
->setFirstname($order->getCustomerFirstname())
->setLastname($order->getCustomerLastname() ?: $order->getCustomerFirstname())
->setMiddlename($order->getCustomerMiddlename())
->setStoreId($order->getStoreId());
// Assuming setPrimaryBillingAddress() and setPrimaryShippingAddress() logic is handled separately,
// as Magento 2 uses addresses linked to customer entities differently than Magento 1
// Add customer addresses
$billingAddress = $this->addressFactory->create()->setData($order->getBillingAddress()->getData());
$shippingAddress = $this->addressFactory->create()->setData($order->getShippingAddress()->getData());
$customer->setAddresses([$billingAddress, $shippingAddress]);
// Convert to Netsuite format and send to Netsuite
// Assuming getNetsuiteFormat is an available method that transforms Magento customer to Netsuite format
$netsuiteCustomer = $this->getNetsuiteFormat($customer);
if ($netsuiteCustomer->externalId == 0) {
$netsuiteCustomer->externalId = null;
}
// Dispatch event before sending customer to Netsuite
$this->eventManager->dispatch(
'netsuite_customer_send_before',
['netsuite_customer' => $netsuiteCustomer]
);
// Send the customer to Netsuite
// Assuming _getNetsuiteService() and the subsequent Netsuite call are implemented
$response = $this->_getNetsuiteService()->add($netsuiteCustomer);
if ($response->writeResponse->status->isSuccess) {
return $response->writeResponse->baseRef->internalId;
} else {
throw new Exception(json_encode($response->writeResponse->status->statusDetail));
}
}
protected function replaceName($value) {
return preg_replace('/[^\p{L}\p{M}\,\-\_\.\'\s\d]/', ' ', $value);
}
/**
* filter first non-empty value from array and return as array.
*
* @param array $array
* @return array
*/
protected function filterFirstNonEmpty($array) {
foreach ($array as $value) {
if ($value != '') {
$value = $this->replaceName($value);
$value = explode(' ', $value);
return $value;
}
}
return [];
}
/**
* Get name from address text.
*
* @param string $address
* @return array
*/
protected function getNameFromAddressText($address) {
if (empty($address)) {
return [];
}
return $this->filterFirstNonEmpty(explode("\n", $address));
}
/**
* Get customer group ID by name.
*
* @param string $name
* @return int
*/
protected function getCustomerGroupIdByName($name) {
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('customer_group_code', $name)
->create();
try {
$customerGroup = $this->groupRepository->getList($searchCriteria)->getItems();
return array_shift($customerGroup)->getId();
} catch (NoSuchEntityException $e) {
throw new LocalizedException(__("Error fetching customer group ID: %1", $e->getMessage()));
}
}
/**
* get wholesale customer group id.
*
* @return int
*/
protected function getDefaultCustomerGroupId() {
if (!isset($this->customerGroupIdMap[$this->default_customer_group])) {
$this->customerGroupIdMap[$this->default_customer_group] = $this->getCustomerGroupIdByName($this->default_customer_group);
}
return $this->customerGroupIdMap[$this->default_customer_group];
}
/**
* Get region by country code and region code.
*
* @param string $countryCode
* @param string $regionCode
* @return \Magento\Directory\Model\Region
*/
protected function getRegion($countryCode, $regionCode) {
try {
$region = $this->regionFactory->create();
$region->loadByCode($regionCode, $countryCode);
return $region ?? '';
} catch (\Exception $e) {
throw new LocalizedException(__("Error fetching region ID: %1", $e->getMessage()));
}
}
}
+517
View File
@@ -0,0 +1,517 @@
<?php
namespace JR\NetSuite\Mapper;
use JR\NetSuite\Mapper\AbstractMapper;
use Magento\Directory\Model\RegionFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use JR\NetSuite\Mapper\CustomerMapper;
use JR\NetSuite\Api\LocationRepositoryInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Tax\Api\TaxRateRepositoryInterface;
// Handles the specifics of mapping order data.
class OrderMapper
{
const ORDER_STATUS_MAPPER = [
'pendingApproval' => 'pending',
'pendingFulfillment' => 'pending',
'cancelled' => 'canceled',
'partiallyFulfilled' => 'processing',
'pendingBillingPartFulfilled' => 'processing',
'pendingBilling' => 'processing',
'fullyBilled' => 'complete',
'closed' => 'closed',
'undefined' => 'undefined'
];
const SHIP_METHOD_MAPPER = [
'freeshipping_freeshipping' => '911',
'will_call' => '911',
'ups_ups' => '1716'
];
/**
* Shipping method mapping from NetSuite to Magento.
*/
const SHIP_METHOD_MAPPER_R = [
// Will Call
'911' => 'instore_pickup', // Will Call
// UPS
'xxxx' => 'ups_11', // UPS Standard
'1716' => 'ups_03', // UPS® Ground
'7074' => 'ups_59', // UPS 2nd Day Air A.M.
'6849' => 'ups_59', // UPS 2nd Day Air A.M.®
'4622' => 'ups_02', // UPS 2nd Day Air®
'7076' => 'ups_12', // UPS 3 Day Select
'6845' => 'ups_12', // UPS 3 Day Select®
'7077' => 'ups_01', // UPS Next Day Air
'6847' => 'ups_01', // UPS Next Day Air®
'4623' => 'ups_01', // UPS Next Day Air Saver® [***Closest Match***]
'4624' => 'ups_14', // UPS Next Day Air® Early A.M.®
'10720' => 'ups_08', // UPS Worldwide Expedited®
'10721' => 'ups_07', // UPS Worldwide Express®
'xxxxx' => 'ups_54', // UPS Worldwide Express Plus
'10722' => 'ups_65', // UPS Worldwide Saver®
// Fedex (Due to Fedex unavailability, flatrate_flatrate will be used)
'4630' => 'flatrate_flatrate', // 'fedex_FEDEX_2_DAY', // FedEx 2Day®
'4633' => 'flatrate_flatrate', // 'fedex_FEDEX_2_DAY_AM', // FedEx 2Day® A.M.
'4632' => 'flatrate_flatrate', // 'fedex_FEDEX_3_DAY_FREIGHT', // FedEx 3Day® Freight
'4631' => 'flatrate_flatrate', // 'fedex_FEDEX_EXPRESS_SAVER', // FedEx Express Saver®
'4627' => 'flatrate_flatrate', // 'fedex_FIRST_OVERNIGHT', // FedEx First Overnight®
'4634' => 'flatrate_flatrate', // 'fedex_FEDEX_1_DAY_FREIGHT', // FedEx First Overnight® Freight [***Closest Match***]
'1717' => 'flatrate_flatrate', // 'fedex_FEDEX_GROUND', // FedEx Ground®
'4626' => 'flatrate_flatrate', // 'fedex_GROUND_HOME_DELIVERY', // FedEx Home Delivery®
'4636' => 'flatrate_flatrate', // 'fedex_INTERNATIONAL_ECONOMY', // FedEx International Economy®
'4635' => 'flatrate_flatrate', // 'fedex_INTERNATIONAL_PRIORITY', // FedEx International Priority®
'4628' => 'flatrate_flatrate', // 'fedex_PRIORITY_OVERNIGHT', // FedEx Priority Overnight®
'4629' => 'flatrate_flatrate', // 'fedex_STANDARD_OVERNIGHT', // FedEx Standard Overnight®
// Others
'4625' => 'flatrate_flatrate', // USPS/Trucking/International
'7369' => 'flatrate_flatrate' // Customer Provided
];
/**
* @var RegionFactory
*/
protected $regionFactory;
/**
* @var int
*/
protected $storeId;
/**
* @var \JR\NetSuite\Helper\Data
*/
protected $helper;
/**
* @var SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;
/**
* @var CustomerMapper
*/
protected $customerMapper;
/**
* @var LocationRepository
*/
protected $locationRepository;
/**
* @var OrderRepositoryInterface
*/
protected $orderRepository;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @var Product
*/
protected $productModel;
/**
* @var GroupRepositoryInterface
*/
protected $groupRepository;
/**
* @var TaxRateRepositoryInterface
*/
protected $taxRateRepository;
/**
* OrderMapper constructor.
*/
public function __construct(
RegionFactory $regionFactory,
\JR\NetSuite\Helper\Data $helper,
SearchCriteriaBuilder $searchCriteriaBuilder,
CustomerMapper $customerMapper,
LocationRepositoryInterface $locationRepository,
OrderRepositoryInterface $orderRepository,
ProductRepositoryInterface $productRepository,
Product $productModel,
GroupRepositoryInterface $groupRepository,
TaxRateRepositoryInterface $taxRateRepository
) {
$this->regionFactory = $regionFactory;
$this->helper = $helper;
$this->storeId = $this->helper->getDefaultStoreId();
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->customerMapper = $customerMapper;
$this->locationRepository = $locationRepository;
$this->orderRepository = $orderRepository;
$this->productRepository = $productRepository;
$this->productModel = $productModel;
$this->groupRepository = $groupRepository;
$this->taxRateRepository = $taxRateRepository;
}
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
public function convertToMagentoFormat($netSuiteData)
{
// convert netsuite data to magento data
$magentoData = [];
foreach ($netSuiteData as $data) {
$convertedData = [
'netsuite_order_location_id' => $data['location'],
'netsuite_order_id' => $data['internalid'],
'netsuite_order_number' => $data['tranid'],
'netsuite_customer_id' => $data['entity'],
'store_id' => $this->storeId,
'email' => $data['email'],
'company' => $data['companyname'],
'status' => self::ORDER_STATUS_MAPPER[$data['status']] ?? 'undefined',
'total' => $data['total'],
'amount' => $data['amount'],
'tax' => $data['taxtotal'],
'shipping_amount' => $data['shippingcost'],
'shipping_description' => $data['shipcarrier'],
'shipping_method' => $data['shipmethod'],
'purchase_date' => $data['datecreated'],
'last_modified_date' => $data['lastmodifieddate'],
'other_ref_num' => $data['otherrefnum'],
];
if ($data['customer'] ?? false) {
$convertedData['customer'] = $this->customerMapper->convertToMagentoFormat([$data['customer']]);
$convertedData['customer'] = reset($convertedData['customer']);
}
// billing address
if ($data['billaddress'] != '') {
$billaddressee = $this->filterFirstNonEmpty([
$data['billattention'],
$data['billaddressee'],
]);
if (empty($billaddressee)) {
$billaddressee = $this->getNameFromAddressText($data['billaddress']);
}
$convertedData['billing_address'] = [
'firstname' => $convertedData['customer']['billing_address']['firstname'] ??
$convertedData['customer']['shipping_address']['firstname'] ??
(count($billaddressee) > 0 ? array_shift($billaddressee) : ''),
'lastname' => $convertedData['customer']['billing_address']['lastname'] ??
$convertedData['customer']['shipping_address']['lastname'] ??
(count($billaddressee) > 0 ? implode(' ', $billaddressee) : $data['companyname']),
'company' => $data['companyname'],
'street' => [!empty($data['billaddress1']) ? $data['billaddress1'] : '-', $data['billaddress2']],
'city' => $data['billcity'],
'country_id' => $data['billcountry'],
'region_id' => $this->getRegion($data['billcountry'], $data['billstate'])->getId(),
'postcode' => !empty($data['billzip']) ? $data['billzip'] : '-' ,
'telephone' => $data['billphone'],
'fax' => '',
'save_in_address_book' => 0
];
}
if ($data['shipaddress'] != '') {
$shipaddressee = $this->filterFirstNonEmpty([
$data['shipattention'],
$data['shipaddressee'],
]);
if (empty($shipaddressee)) {
$shipaddressee = $this->getNameFromAddressText($data['shipaddress']);
}
$convertedData['shipping_address'] = [
'firstname' => $convertedData['customer']['shipping_address']['firstname'] ??
$convertedData['customer']['billing_address']['firstname'] ??
(count($shipaddressee) > 0 ? array_shift($shipaddressee) : ''),
'lastname' => $convertedData['customer']['shipping_address']['lastname'] ??
$convertedData['customer']['billing_address']['lastname'] ??
(count($shipaddressee) > 0 ? implode(' ', $shipaddressee) : $data['companyname']),
'company' => $data['companyname'],
'street' => [!empty($data['shipaddress1']) ? $data['shipaddress1'] : '-', $data['shipaddress2']],
'city' => $data['shipcity'],
'country_id' => $data['shipcountry'],
'region_id' => $this->getRegion($data['shipcountry'], $data['shipstate'])->getId(),
'postcode' => $data['shipzip'],
'telephone' => $data['shipphone'],
'fax' => '',
'save_in_address_book' => 0
];
if (
isset($convertedData['shipping_address'])
&& !empty($convertedData['shipping_address']['firstname'])
&& ($convertedData['shipping_address']['firstname'][0] ?? '' == $convertedData['shipping_address']['street'][0][0] ?? '')
&& isset($convertedData['billing_address'])
) {
$convertedData['shipping_address']['firstname'] = $convertedData['billing_address']['firstname'];
$convertedData['shipping_address']['lastname'] = $convertedData['billing_address']['lastname'];
}
}
// item
$convertedData['items'] = [];
foreach ($data['items'] as $item) {
$convertedData['items'][] = [
'netsuite_order_item_id' => $item['itemId'],
'sku' => $item['itemText'],
'description' => $item['description'],
'qty' => $item['quantity'],
'type' => $item['type'],
'price' => $item['rate'],
'amount' => $item['amount'],
];
}
// payment
$convertedData['payment'] = [
'method' => $data['paymentmethod'],
'paid_amount' => $data['paidamount'],
'date_paid' => $data['paymenteventdate'],
'status' => $data['paymenteventresult'],
'type' => $data['paymenteventtype'],
// 'cc_type' => '',
// 'cc_number_enc' => '',
// 'cc_last4' => '',
// 'cc_owner' => '',
// 'cc_exp_month' => '',
// 'cc_exp_year' => '',
// 'cc_ss_start_month' => '',
// 'cc_ss_start_year' => '',
// 'cc_ss_issue' => '',
];
$magentoData[] = $convertedData;
}
return $magentoData;
}
/**
* Convert data from Magento format to NetSuite format.
*
* @param \Magento\Sales\Model\Order $order
* @return array
*/
public function convertToNetSuiteFormat($order)
{
$data = $this->initializeData($order);
$data['items'] = $this->getOrderItems($order);
return $data;
}
/**
* Initialize variables.
*
* @param \Magento\Sales\Model\Order $order
* @param string $netsuiteCustomerId
* @return array
*/
protected function initializeData($order, $netsuiteCustomerId = '')
{
$shippingAddress = $order->getShippingAddress();
$billingAddress = $order->getBillingAddress();
$phone = preg_replace('/[^0-9]/', '', $shippingAddress->getTelephone());
if (strlen($phone) == 10) {
$phone = '0001' . $phone;
}
$phone = str_pad($phone, 14, '0', STR_PAD_LEFT);
try {
$region = $this->regionFactory->create();
$region->loadByName($shippingAddress->getRegion(), $shippingAddress->getCountryId());
} catch (\Exception $e) {
$region = null;
}
$address = [
'country' => $shippingAddress->getCountryId(),
'city' => $shippingAddress->getCity(),
'state' => $region?->getCode() ?? '',
'zip' => $shippingAddress->getPostcode(),
'addressee' => $shippingAddress->getCompany(),
'attention' => $shippingAddress->getFirstname() . ' ' . $shippingAddress->getLastname(),
'addrphone' => $phone,
'addr1' => $shippingAddress->getStreetLine(1),
'addr2' => $shippingAddress->getStreetLine(2),
];
$payment = $order->getPayment();
$cardInfo = [
'Card #' => '******' . $payment->getCcLast4(),
'Billing address' => implode(', ', array_filter($billingAddress->getStreet())) . ', ' . $billingAddress->getCity() . ', ' . $billingAddress->getRegionCode() . ' ' . $billingAddress->getPostcode() . ', ' . $billingAddress->getCountryId(),
'Card Holder Name' => $billingAddress->getFirstname() . ' ' . $billingAddress->getLastname(),
];
$cardInfo = implode("\n", array_map(function ($key, $value) {
return $key . ': ' . $value;
}, array_keys($cardInfo), $cardInfo));
$phone = preg_replace('/[^0-9]/', '', $shippingAddress->getTelephone() ?? '');
$phone = substr($phone, strlen($phone) - 10, 10);
// get location id based on shipping address
$locationId = $this->getLocationId($shippingAddress->getCity());
if (!$locationId) {
$locationId = $this->getLocationId($region?->getCode() ?? '');
}
$vars = [
'note' => $order->getCustomerNote() ?? '',
'address' => $address,
'orderNo' => $order->getIncrementId(),
'cardInfo' => $cardInfo,
'terms' => '12',
'phone' => $phone,
'custId' => $netsuiteCustomerId, // TODO: get customer ID from NetSuite
'company' => $order->getBillingAddress()->getCompany(),
'location' => '222', // TODO: get location from config
'shipmethod' => self::SHIP_METHOD_MAPPER[$order->getShippingMethod()],
'shippingcost' => $order->getShippingAmount(),
// TODO: get entity from NetSuite
// 'entity' => $netsuiteEntityId,
'email' => $order->getCustomerEmail(),
// 'customer' => $this->customerMapper->convertToNetSuiteFormatByEmail($order->getCustomerEmail()),
];
if ($order->getDiscountAmount() < 0) {
$vars['discountItem'] = $order->getDiscountAmount();
$vars['discountRate'] = round(($order->getDiscountAmount() / $order->getGrandTotal()) * 100, 2);
}
return $vars;
}
/**
* search location list by name
*/
protected function getLocationId($name)
{
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('is_active', 1)
->addFilter('name', $name)
->create();
$locations = $this->locationRepository->getList($searchCriteria)->getItems();
if (count($locations) > 0) {
$location = reset($locations);
return $location->getLocationId() ?? '';
}
return '';
}
/**
* get order by field and value.
*
* @param string $field
* @return \Magento\Sales\Model\Order | null
*/
public function getOrderBy($field, $value)
{
$searchCriteria = $this->searchCriteriaBuilder
->addFilter($field, $value)
->create();
$orders = $this->orderRepository->getList($searchCriteria)->getItems();
$order = count($orders) > 0 ? reset($orders) : null;
return $order;
}
/**
* Get order items.
*
* @param \Magento\Sales\Model\Order $order
* @return array
*/
protected function getOrderItems($order)
{
$items = [];
foreach ($order->getAllItems() as $item) {
$product = $this->productModel->load($item->getProductId());
$items[] = [
'id' => $product->getCustomAttribute('netsuite_id')?->getValue() ?? '',
'quantity' => $item->getQtyOrdered(),
'rate' => $item->getPrice(),
];
}
return $items;
}
/**
* filter first non-empty value from array and return as array.
*
* @param array $array
* @return array
*/
protected function filterFirstNonEmpty($array)
{
foreach ($array as $value) {
if ($value != '') {
$value = preg_replace('/[^\p{L}\p{M}\,\-\_\.\'\s\d]/', ' ', $value);
$value = explode(' ', $value);
return $value;
}
}
return [];
}
/**
* Get name from address text.
*
* @param string $address
* @return array
*/
protected function getNameFromAddressText($address)
{
if (empty($address)) {
return [];
}
return $this->filterFirstNonEmpty(explode("\n", $address));
}
/**
* Get region by country code and region code.
*
* @param string $countryCode
* @param string $regionCode
* @return \Magento\Directory\Model\Region
*/
protected function getRegion($countryCode, $regionCode)
{
try {
$region = $this->regionFactory->create();
$region->loadByCode($regionCode, $countryCode);
return $region;
} catch (\Exception $e) {
throw new LocalizedException(__("Error fetching region ID: %1", $e->getMessage()));
}
}
/**
* Convert a given NetSuite shipping method to a corresponding Magento shipping method.
* If the given NetSuite shipping method does not exist in the mapping, 'flatrate_flatrate'
* will be returned.
*
* @param string $nsShipMethod NetSuite ship method internal ID.
* @return string
*/
public function parseNetSuiteShippingMethod($nsShipMethod)
{
if (array_key_exists($nsShipMethod, self::SHIP_METHOD_MAPPER_R)) {
return self::SHIP_METHOD_MAPPER_R[$nsShipMethod];
}
return 'flatrate_flatrate';
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace JR\NetSuite\Mapper;
use JR\NetSuite\Mapper\AbstractMapper;
// Handles the specifics of mapping product data.
class ProductMapper {
/**
* ProductMapper constructor.
*/
public function __construct(
) {
}
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
public function convertToMagentoFormat($netSuiteData) {
// convert netsuite data to magento data
$magentoData = [];
foreach($netSuiteData as $data) {
$magentoData[] = [
'netsuite_product_id' => $data['internalid'],
'sku' => $data['itemid'],
// 'type' => $data['includechildren'] ? 'configurable' : 'simple',
// 'category' => $data['category'],
'name' => $data['displayname'] == '' ? $data['itemid'] : $data['displayname'],
'description' => $data['salesdescription'],
'status' => $data['isinactive'],
// 'vendor' => $data['vendor'],
// 'manufacturer' => $data['manufacturer'],
'upc' => $data['upccode'],
// 'mpn' => $data['mpn'],
// 'tax_class' => $data['taxschedule'],
'weight' => $data['weight'] ?? 1,
// 'weight_unit' => $data['weightunit'],
// 'cost' => $data['cost'],
'price' => $data['baseprice'] != '' ? $data['baseprice'] : 0,
'qty' => (int) ($data['locationquantityavailable'] ?? $data['quantityavailable'] ?? 0),
'locationId' => $data['inventorylocation'] ?? '',
'custitem_item_eol_for_sales' => $data['custitem_item_eol_for_sales'] ?? false,
// 'is_in_stock' => ($data['quantityavailable'] ?? 0) > 0 ? 1 : 0,
// 'created_at' => $data['createddate'],
// 'updated_at' => $data['lastmodifieddate']
];
}
return $magentoData;
}
/**
* Convert data from Magento format to NetSuite format.
*
* @param array $magentoData
* @return array
*/
public function convertToNetSuiteFormat($magentoData) {
// Your conversion logic here
}
}
+229
View File
@@ -0,0 +1,229 @@
<?php
namespace JR\NetSuite\Mapper;
use JR\NetSuite\Mapper\AbstractMapper;
use JR\NetSuite\Helper\Data as Helper;
use Magento\Catalog\Api\ProductRepositoryInterface;
use \Mirasvit\Rma\Api\Repository\RmaRepositoryInterface;
use \Mirasvit\Rma\Api\Service\Rma\RmaManagementInterface;
use \Mirasvit\Rma\Api\Service\Item\ItemListBuilderInterface;
use \Mirasvit\Rma\Api\Service\Item\ItemManagementInterface;
// Handles the specifics of mapping rma data.
class RmaMapper
{
public const STATUS_MAP = [
'pending-approval' => 'pending',
'Pending-receipt' => 'pending',
'partially-received' => 'pending',
'pending-refund/partially-received' => 'pending',
'pending-refund' => 'pending',
'refunded' => 'refunded',
'cancelled' => 'closed',
'closed' => 'closed',
'pendingApproval' => 'pending',
'pendingReceipt' => 'pending',
'partiallyReceived' => 'pending',
'pendingRefund/partiallyReceived' => 'pending',
'pendingRefund' => 'pending',
];
/**
* @var Helper
*/
protected $helper;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @var RmaRepositoryInterface
*/
protected $rmaRepository;
/**
* @var RmaManagementInterface
*/
protected $rmaManagement;
/**
* @var ItemListBuilderInterface
*/
protected $itemListBuilder;
/**
* @var ItemManagementInterface
*/
protected $itemManagement;
/**
* @var \JR\NetSuite\Mapper\CustomerMapper
*/
private $customerMapper;
/**
* RmaMapper constructor.
*
* @param RmaRepositoryInterface $rmaRepository
* @return void
*/
public function __construct(
Helper $helper,
ProductRepositoryInterface $productRepository,
RmaRepositoryInterface $rmaRepository,
RmaManagementInterface $rmaManagement,
ItemListBuilderInterface $itemListBuilder,
ItemManagementInterface $itemManagement,
\JR\NetSuite\Mapper\CustomerMapper $customerMapper
) {
$this->helper = $helper;
$this->productRepository = $productRepository;
$this->rmaRepository = $rmaRepository;
$this->rmaManagement = $rmaManagement;
$this->itemListBuilder = $itemListBuilder;
$this->itemManagement = $itemManagement;
$this->customerMapper = $customerMapper;
}
/**
* Convert data from NetSuite format to Magento format.
*
* @param array $netSuiteData
* @return array
*/
public function convertToMagentoFormat($netSuiteData)
{
// convert netsuite data to magento data
$magentoData = [];
foreach ($netSuiteData as $data) {
$magentoData[] = [
'netsuite_id' => $data['internalid'],
'netsuite_tran_id' => $data['tranid'],
'recorded_at' => $data['datecreated'],
'netsuite_order_id' => $data['createdfrom'],
'netsuite_order_number' => $data['custbody_sales_order'],
'transaction_date' => $data['trandate'],
'status' => self::STATUS_MAP[$data['status']] ?? 'pending',
'customer' => $this->customerMapper->convertToMagentoFormat([$data['customer']])[0] ?? [],
'billaddress' => $data['billaddress'],
'billaddress1' => $data['billaddress1'],
'billaddress2' => $data['billaddress2'],
'billcity' => $data['billcity'],
'billcountry' => $data['billcountry'],
'billstate' => $data['billstate'],
'billzip' => $data['billzip'],
'billphone' => $data['billphone'],
'shipaddress' => $data['shipaddress'],
'shipaddress1' => $data['shipaddress1'],
'shipaddress2' => $data['shipaddress2'],
'shipcity' => $data['shipcity'],
'shipcountry' => $data['shipcountry'],
'shipstate' => $data['shipstate'],
'shipzip' => $data['shipzip'],
'shipphone' => $data['shipphone'],
'total' => $data['total'],
'taxtotal' => $data['taxtotal'],
'shippingcost' => $data['shippingcost'],
'discountamount' => $data['discountamount'],
'amount' => $data['amount'],
'location' => $data['location'],
'return_address' => $data['custbody_return_address_proxy'],
'notes' => $data['custbody_notes'],
'internal_notes' => $data['custbody_internal_notes'],
'items' => $this->convertItems($data),
];
}
return $magentoData;
}
/**
* Convert items from NetSuite format to Magento format.
*
* @param array $data
* @return array
*/
protected function convertItems($data)
{
$items = $data['items'];
$result = [];
foreach ($items as $item) {
$result[] = [
'sku' => $item['itemText'],
'netsuite_id' => $item['itemId'],
'name' => $item['itemText'],
'type' => $item['type'],
'description' => $item['description'],
'qty' => $item['quantity'],
'qty_billed' => $item['quantitybilled'],
'reason' => $item['reasonCode'],
'condition' => $item['conditions'],
'resolution' => $data['custbody_request_type'],
'rate' => $item['rate'],
'amount' => $item['amount'],
'discountamount' => $item['discountamount'],
];
}
return $result;
}
/**
* Convert data from Magento format to NetSuite format.
*
* @param string $rmaId
* @return array
*/
public function convertToNetSuiteFormat($rmaId)
{
$rma = $this->rmaRepository->get($rmaId);
$order = $this->rmaManagement->getOrder($rma);
$customer = $this->rmaManagement->getCustomer($rma);
$result = [
'orderId' => $order->getNetsuiteId(),
'createdAt' => $this->helper->convertLocalTimeToUtc($rma->getCreatedAt(), 'm/d/Y'),
'status' => $this->rmaManagement->getStatus($rma)->getCode(),
'customerId' => $customer->getNetsuiteId(),
'items' => $this->getRmaItems($rma),
];
return $result;
}
/**
* Get RMA items.
*
* @param RmaInterface $rma
* @return array
*/
protected function getRmaItems($rma)
{
$items = $this->itemListBuilder->getRmaItems($rma);
$result = [];
foreach ($items as $item) {
if (!$item->getQtyRequested()) {
continue;
}
$orderItem = $this->itemManagement->getOrderItem($item);
$product = $this->productRepository->getById($orderItem->getProductId());
$result[] = [
'id' => $product->getCustomAttribute('netsuite_id')?->getValue() ?? '',
'sku' => $product->getSku(),
'reason' => $this->itemManagement->getReasonName($item),
'condition' => $this->itemManagement->getConditionName($item),
'resolution' => $this->itemManagement->getResolutionName($item),
'rate' => $orderItem->getPrice(),
'qty' => $item->getQtyRequested(),
'amount' => $orderItem->getPrice() * $item->getQtyRequested(),
'tax_percent' => $orderItem->getTaxPercent(),
'tax_amount' => $orderItem->getTaxPercent() / 100 * $orderItem->getPrice() * $item->getQtyRequested(),
];
}
return $result;
}
}