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
@@ -0,0 +1,76 @@
<?php
/**
* @author 18th DigiTech Team
* @copyright Copyright (c) 2020 18th DigiTech (https://www.18thdigitech.com)
* @package Caratlane_NetSuite
*/
namespace Caratlane\NetSuite\Model\Config\Attribute\Source;
use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;
use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface;
use Magento\Framework\Data\OptionSourceInterface;
/**
* Product status functionality model
*
* @api
* @since 100.0.2
*/
class Status extends AbstractSource implements SourceInterface, OptionSourceInterface
{
/**#@+
* Product Status values
*/
const STATUS_SUCCESS = 1;
const STATUS_FAILED = 0;
/**#@-*/
/**
* Retrieve Visible Status Ids
*
* @return int[]
*/
public function getVisibleStatusIds()
{
return [self::STATUS_SUCCESS];
}
/**
* Retrieve Saleable Status Ids
* Default Product Enable status
*
* @return int[]
*/
public function getSaleableStatusIds()
{
return [self::STATUS_SUCCESS];
}
/**
* Retrieve option array
*
* @return string[]
*/
public function getOptionArray()
{
return [self::STATUS_SUCCESS => __('Success'), self::STATUS_FAILED => __('Failed')];
}
/**
* Retrieve option array with empty value
*
* @return string[]
*/
public function getAllOptions()
{
$result = [];
foreach (self::getOptionArray() as $index => $value) {
$result[] = ['value' => $index, 'label' => $value];
}
return $result;
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
/**
* @author 18th DigiTech Team
* @copyright Copyright (c) 2020 18th DigiTech (https://www.18thdigitech.com)
* @package Caratlane_NetSuite
*/
namespace Caratlane\NetSuite\Model\Config;
class CronConfig extends \Magento\Framework\App\Config\Value
{
const CRON_STRING_PATH = 'crontab/default/jobs/caratlane_netsuite_cron_job/schedule/cron_expr';
const CRON_MODEL_PATH = 'crontab/default/jobs/caratlane_netsuite_cron_job/run/model';
protected $_configValueFactory;
protected $_runModelPath = '';
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\Framework\App\Config\ValueFactory $configValueFactory,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
$runModelPath = '',
array $data = []
) {
$this->_runModelPath = $runModelPath;
$this->_configValueFactory = $configValueFactory;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
public function afterSave()
{
$time = $this->getData('netsuite/cronScheduled/fields/time/value');
$frequency = $this->getData('netsuite/cronScheduled/fields/frequency/value');
$t1 = isset($time[1])?$time[1]:0;
$t2 = isset($time[0])?$time[0]:0;
$cronExprArray = [
(int)($t1),
(int)($t2),
$frequency == \Magento\Cron\Model\Config\Source\Frequency::CRON_MONTHLY ? '1' : '*',
'*',
$frequency == \Magento\Cron\Model\Config\Source\Frequency::CRON_WEEKLY ? '1' : '*',
];
$cronExprString = join(' ', $cronExprArray);
try {
$this->_configValueFactory->create()->load(
self::CRON_STRING_PATH,
'path'
)->setValue(
$cronExprString
)->setPath(
self::CRON_STRING_PATH
)->save();
$this->_configValueFactory->create()->load(
self::CRON_MODEL_PATH,
'path'
)->setValue(
$this->_runModelPath
)->setPath(
self::CRON_MODEL_PATH
)->save();
} catch (\Exception $e) {
//throw new \Exception(__('We can\'t save the cron expression.'));
$e->getMessage();
}
return parent::afterSave();
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
/**
* @author 18th DigiTech Team
* @copyright Copyright (c) 2020 18th DigiTech (https://www.18thdigitech.com)
* @package Caratlane_NetSuite
*/
namespace Caratlane\NetSuite\Model;
class NetSuite extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface
{
const CACHE_TAG = 'netsuite_order_log';
protected $_cacheTag = 'netsuite_order_log';
protected $_eventPrefix = 'netsuite_order_log';
protected function _construct()
{
$this->_init(\Caratlane\NetSuite\Model\ResourceModel\NetSuite::class);
}
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
public function getDefaultValues()
{
$values = [];
return $values;
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model;
class NetSuiteConstants
{
const NETSUITE_TRACK_SHIPMENT_LOG_FILENAME = 'track_shipment';
const NETSUITE_TRACK_ORDER_LOG_FILENAME = 'track_order';
const NETSUITE_ORDER_UPODATE_LOG_FILENAME = 'order_update';
const NETSUITE_CREATE_SHIPMENT_LOG_FILENAME = 'create_shipment';
const NETSUITE_CREATE_UPDATEPDF_LOG_FILENAME = 'update_invoicepdf';
const NETSUITE_LOG_DIR = '/netsuite/';
const NETSUITE_DEFAULT_ERROR_CODE = 'false';
const NETSUITE_DEFAULT_SUCCESS_CODE = 'true';
const NETSUITE_DEFAULT_STATUS = 'pending';
const NETSUITE_EMPTY_MESSAGE = 'The request data is empty or invalid.';
const NETSUITE_SUCCESS_MESSAGE = 'Data saved successfully. Import process will be start soon.';
const NETSUITE_MIGRATION_STATUS = 'success';
const NETSUITE_MIGRATION_FAILED_STATUS = 'failed';
const NETSUITE_MIGRATION_SUCCESS_MESSAGE = 'Shipment data inserted successfully.';
const NETSUITE_MIGRATION_ORDER_INDERTED_SUCCESS_MESSAGE = 'Order update data inserted successfully.';
const NETSUITE_MIGRATION_SHIPMENT_SUCCESS_MESSAGE = 'Shipment created successfully.';
const NETSUITE_MIGRATION_SHIPMENT_UPDATE_SUCCESS_MESSAGE = 'Shipment status update successfully.';
const NETSUITE_MIGRATION_ORDER_SUCCESS_MESSAGE = 'Order status update successfully.';
const NETSUITE_MIGRATE_CREATE_SHIPMENT_LOG_FILENAME = 'create_shipment_process';
const NETSUITE_MIGRATE_TRACK_SHIPMENT_LOG_FILENAME = 'track_shipment_process';
const NETSUITE_MIGRATE_TRACK_ORDER_LOG_FILENAME = 'order_update_process';
const NETSUITE_TRACKING_CODE = 'custom';
const NETSUITE_DISABLE_MESSAGE = 'This feature has been disable. Please contact to service provider.';
const CAN_NOT_CANCEL_ORDER = 'Can not canceled order due invoice or shipment has been created';
const CAN_NOT_HOLDED_ORDER = 'Can not hold order due invoice or shipment has been created';
const NETSUITE_CANCEL_MESSAGE = 'Order has been canceled successfully';
const NETSUITE_ORDER_NOT_FOUND = 'Order not found';
const STATUS_ARRAY_LIST = ['canceled','holded','shipped','delivered'];
}
+35
View File
@@ -0,0 +1,35 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model;
use Magento\Framework\Model\AbstractModel;
class NetSuiteOrdersUpdate extends AbstractModel
{
/**
* Define resource model
*/
protected function _construct()
{
$this->_init(\Caratlane\NetSuite\Model\ResourceModel\NetSuiteOrdersUpdate::class);
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model;
use Magento\Framework\Model\AbstractModel;
class NetsuiteShipments extends AbstractModel
{
/**
* Define resource model
*/
protected function _construct()
{
$this->_init(\Caratlane\NetSuite\Model\ResourceModel\NetsuiteShipments::class);
}
}
@@ -0,0 +1,35 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model;
use Magento\Framework\Model\AbstractModel;
class NetsuiteUpdateinvoicepdf extends AbstractModel
{
/**
* Define resource model
*/
protected function _construct()
{
$this->_init(\Caratlane\NetSuite\Model\ResourceModel\NetsuiteUpdateinvoicepdf::class);
}
}
+200
View File
@@ -0,0 +1,200 @@
<?php
/**
* @author 18th DigiTech Team
* @copyright Copyright (c) 2020 18th DigiTech (https://www.18thdigitech.com)
* @package Caratlane_NetSuite
*/
namespace Caratlane\NetSuite\Model;
use Magento\Store\Model\ScopeInterface;
class Oauth
{
const SIGNATURE_METHOD_HMACSHA256 = 'HMAC-SHA256';
const OAUTH_SCRIPT = 'netsuite/apidetail/script';//'694';
const OAUTH_VERSION = '1.0';
const NONCE_STRING = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const XML_PATH_OAUTH_REALM = 'netsuite/apidetail/oauth_realm';
const XML_PATH_OAUTH_CONSUMER_KEY = 'netsuite/apidetail/oauth_consumer_key';
const XML_PATH_OAUTH_CONSUMER_SECRET = 'netsuite/apidetail/oauth_consumer_secret';
const XML_PATH_OAUTH_TOKEN = 'netsuite/apidetail/oauth_token';
const XML_PATH_OAUTH_TOKEN_SECRET = 'netsuite/apidetail/oauth_token_secret';
const XML_PATH_OAUTH_URL = 'netsuite/cronScheduled/api_url';
/**
* @var storeManager
*/
protected $storeManager;
/**
* @var scopeConfig
*/
protected $scopeConfig;
/**
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
**/
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
) {
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
}
/*
* consumer key
* @return string
*/
public function getConsumerKey()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_CONSUMER_KEY);
}
/*
* consumer Secret
* @return string
*/
public function getConsumerSecret()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_CONSUMER_SECRET);
}
/*
* Token access key
* @return string
*/
public function getToken()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_TOKEN);
}
/*
* Token Secret
* @return string
*/
public function getTokenSecret()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_TOKEN_SECRET);
}
/*
* Token Secreat
* @return string
*/
public function getRealm()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_REALM);
}
/*
* Token script
* @return string
*/
public function getScript()
{
return $this->getConfigValue(self::OAUTH_SCRIPT);
}
/*
* Token Secreat
* @return string
*/
public function getApiUrl()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_URL);
}
/*
* Calculate header for request
* @return string
*/
public function getOauthParams()
{
$time = time();
$nonce = rawurlencode($this->generateNonceString(11));
$oauthparams = $this->getParamObject($nonce, $time);
$baseString = $this->createBaseString($oauthparams);
$signature = $this->getSignature('sha256', $baseString);
return $headerValue = $this->buildAuthorizationHeader($nonce, $time, $signature);
}
/*
* Calculate signature for request
* @return string
*/
public function getSignature($algo, $baseString)
{
$key = rawurlencode($this->getConsumerSecret()) . '&' . rawurlencode($this->getTokenSecret());
return rawurlencode(base64_encode(hash_hmac($algo, $baseString, $key, true)));
}
/**
* Builds the Authorization header for a request
* @return array
*/
private function buildAuthorizationHeader($nonce, $time, $signature)
{
return 'OAuth realm="'.$this->getRealm().'", oauth_consumer_key="'.$this->getConsumerKey().'",oauth_nonce="'.$nonce.'",oauth_signature_method="HMAC-SHA256",oauth_timestamp="'.$time.'",oauth_token="'.$this->getToken().'",oauth_version="1.0",oauth_signature="'.$signature.'"';
}
/**
* Creates the Signature Base String.
* The Signature Base String is a consistent reproducible concatenation of
* the request elements into a single string. The string is used as an
* input in hashing or signing algorithms.
* @return string Returns the base string
*/
private function createBaseString($params)
{
$url = $this->getApiUrl();
$query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
return strtoupper('POST')
. '&' . rawurlencode($url)
. '&' . rawurlencode($query);
}
/*
* generating nonce value
* @return string
*/
public function generateNonceString($length = 11)
{
$characters = self::NONCE_STRING;
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
/*
* generating param value
* @return array
*/
public function getParamObject($nonce, $time)
{
return [
'deploy'=>1,
"oauth_consumer_key"=> $this->getConsumerKey(),
"oauth_nonce"=> $nonce,
"oauth_signature_method"=>self::SIGNATURE_METHOD_HMACSHA256,
"oauth_timestamp"=> $time,
"oauth_token"=>$this->getToken(),
"oauth_version"=> self::OAUTH_VERSION,
'script'=> $this->getScript()
];
}
/*
* get config value
* return string
*/
public function getConfigValue($path)
{
$store = $this->storeManager->getStore()->getStoreId();
$config_data = $this->scopeConfig->getValue($path, ScopeInterface::SCOPE_STORE, $store);
return $config_data;
}
}
+226
View File
@@ -0,0 +1,226 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model\Order;
use Magento\Framework\Webapi\Rest\Request;
use Caratlane\NetSuite\Api\OrderUpdateInterface;
use Caratlane\NetSuite\Model\NetSuiteOrdersUpdateFactory;
use Caratlane\NetSuite\Model\NetSuiteConstants;
use Caratlane\NetSuite\Helper\Logger;
use Caratlane\NetSuite\Helper\Data;
use Magento\Framework\App\ResourceConnection;
use Magento\Sales\Api\Data\OrderInterface;
class OrderUpdate implements OrderUpdateInterface
{
/**
* @var \Magento\Framework\App\ResourceConnection
*/
private $resource;
/**
* @var \Magento\Sales\Api\Data\OrderInterface
*/
private $orderInterface;
/**
* @var \Caratlane\NetSuite\Helper\Logger
*/
protected $logger;
/**
* @var \Magento\Framework\Webapi\Rest\Request
*/
private $request;
/**
* @var \Caratlane\NetSuite\Model\NetSuiteOrdersUpdateFactory
*/
private $netSuiteOrdersUpdate;
/**
* @var \Caratlane\NetSuite\Helper\Data
*/
private $helper;
/**
* @param ResourceConnection $resource
* @param OrderInterface $orderInterface
* @param Data $helper
* @param Logger $logger
* @param Request $request
* @param NetSuiteOrdersUpdateFactory $netSuiteOrdersUpdate
*/
public function __construct(
Data $helper,
Logger $logger,
Request $request,
ResourceConnection $resource,
OrderInterface $orderInterface,
NetSuiteOrdersUpdateFactory $netSuiteOrdersUpdate
) {
$this->logger = $logger;
$this->helper = $helper;
$this->request = $request;
$this->resource = $resource;
$this->orderInterface = $orderInterface;
$this->netSuiteOrdersUpdate = $netSuiteOrdersUpdate;
}
public function getOrderUpdate()
{
$responseData = [];
$responseData['success'] = NetSuiteConstants::NETSUITE_DEFAULT_ERROR_CODE;
$responseData['message'] = NetSuiteConstants::NETSUITE_DISABLE_MESSAGE;
if ($this->helper->getNetSuiteIsEnabled() && $this->helper->getNetsuiteOrdersUpdateEnabled()) {
$responseData['message'] = NetSuiteConstants::NETSUITE_EMPTY_MESSAGE;
$postData = $this->request->getBodyParams();
$this->logger->initLog(NetSuiteConstants::NETSUITE_ORDER_UPODATE_LOG_FILENAME);
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('Order Update Started');
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('');
try {
if (!empty($postData)) {
if ($postData['ns_order_id']) {
$this->logger->writeLog('Magento Order Id: '.$postData['magento_order_id']);
if (!$postData['ns_order_id'] || !$postData['magento_order_id'] || !$postData['order_status']) {
$this->logger->writeLog('Please add required fields');
$responseData['success'] = false;
$responseData['message'] = "Please add required fields";
return [$responseData];
}
$incrementOrderId = $this->getOrderId($postData['magento_order_id']);
if ($incrementOrderId != "") {
$jsondata = json_encode($postData);
$netSuiteOrderUpdateModel = $this->netSuiteOrdersUpdate->create();
$netSuiteOrderUpdateModel->setMagentoOrderId($postData['magento_order_id']);
$netSuiteOrderUpdateModel->setNetsuiteOrderId($postData['ns_order_id']);
$netSuiteOrderUpdateModel->setNetsuiteOrderStatus($postData['order_status']);
$netSuiteOrderUpdateModel->setStatus("completed");
$netSuiteOrderUpdateModel->setJsonData($jsondata);
$orderstatusmsg = NetSuiteConstants::NETSUITE_MIGRATION_ORDER_INDERTED_SUCCESS_MESSAGE;
$netSuiteOrderUpdateModel->setMessages($orderstatusmsg);
$netSuiteOrderUpdateModel->save();
//update data for shipment table
$connection = $this->resource->getConnection();
$data = [];
$data['netsuite_order_status'] = $postData['order_status'];
$where = ['increment_id = ?' => $postData['magento_order_id']];
/* update sales_shipment_grid */
$tableName = $connection->getTableName("sales_order_grid");
$connection->update($tableName, $data, $where);
/* update sales_shipment */
$tableName = $connection->getTableName("sales_order");
$connection->update($tableName, $data, $where);
$this->logger->writeLog('Order Status: '.$postData['order_status']);
/* update sales_order_item */
$orderId = $this->getOrderId($postData['magento_order_id']);
$itemarray = $postData['items'];
$this->updateOrderItem($itemarray, $orderId);
$this->logger->writeLog('Order updated successfully');
$responseData['success'] = true;
$responseData['message'] = "Order updated successfully";
$responseData['magento_order_id'] = $postData['magento_order_id'];
} else {
$this->logger->writeLog('Order id not found in system ='.$postData['magento_order_id']);
$responseData['success'] = false;
$responseData['message'] = "Order id not found in system";
}
} else {
$this->logger->writeLog('ns_order_id field can\'t be empty');
$responseData['success'] = false;
$responseData['message'] = "ns_order_id field can't be empty";
}
} else {
$this->logger->writeLog('Order Update Data Not Found');
}
} catch (Exception $e) {
$this->logger->writeLog('Exception: '.$e->getMessage());
$responseData['success'] = false;
$responseData['message'] = 'Exception : '.$e->getMessage();
}
$this->logger->writeLog('');
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('Order Update Stopped');
$this->logger->writeLog('----------------------------');
}
return [$responseData];
}
private function updateOrderItem($itemarray, $orderId)
{
if (!empty($itemarray)) {
foreach ($itemarray as $key => $orderitem) {
$dataitem = [];
$itemconnection = $this->resource->getConnection();
$dataitem['qty_shipped'] = $orderitem['qty_shipped'];
$dataitem['qty_canceled'] = $orderitem['qty_cancelled'];
$dataitem['qty_refunded'] = $orderitem['qty_refunded'];
$dataitem['qty_delivered'] = $orderitem['qty_delivered'];
$dataitem['netsuite_item_status'] = $orderitem['item_status'];
$itemwhere = ['order_id = ?' => (int)$orderId,'sku = ?' => $orderitem['item_sku']];
$itemtableName = $itemconnection->getTableName("sales_order_item");
$itemconnection->update($itemtableName, $dataitem, $itemwhere);
$this->logger->writeLog('Order Item Sku: '.$orderitem['item_sku']);
$this->logger->writeLog('Order Item Status: '.$orderitem['item_status']);
}
}
}
public function getOrderId(string $incrementOrderId)
{
$orderId = 0;
try {
$orderInfo = $this->orderInterface->loadByIncrementId($incrementOrderId);
$orderId = $orderInfo->getId();
return $orderId;
} catch (Exception $e) {
return $orderId;
}
}
}
@@ -0,0 +1,106 @@
<?php
/**
* @author 18th DigiTech Team
* @copyright Copyright (c) 2020 18th DigiTech (https://www.18thdigitech.com)
* @package Caratlane_NetSuite
*/
namespace Caratlane\NetSuite\Model\Order\Payment\State;
use Magento\Framework\App\ObjectManager;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderPaymentInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\StatusResolver;
/**
* Process order state and status after capture operation.
*/
class CaptureCommand extends \Magento\Sales\Model\Order\Payment\State\CaptureCommand
{
/**
* @var StatusResolver
*/
private $statusResolver;
/**
* @param StatusResolver|null $statusResolver
*/
public function __construct(StatusResolver $statusResolver = null)
{
parent::__construct($statusResolver);
$this->statusResolver = $statusResolver
? : ObjectManager::getInstance()->get(StatusResolver::class);
}
/**
* Run command.
*
* @param OrderPaymentInterface $payment
* @param string|float $amount
* @param OrderInterface $order
* @return \Magento\Framework\Phrase
*/
public function execute(OrderPaymentInterface $payment, $amount, OrderInterface $order)
{
$state = Order::STATE_NEW;
$status = null;
$message = 'Captured amount of %1 online.';
if ($payment->getIsTransactionPending()) {
$state = Order::STATE_PAYMENT_REVIEW;
$message = 'An amount of %1 will be captured after being approved at the payment gateway.';
}
if ($payment->getIsFraudDetected()) {
$state = Order::STATE_PAYMENT_REVIEW;
$status = Order::STATUS_FRAUD;
$message .= ' Order is suspended as its capturing amount %1 is suspected to be fraudulent.';
}
$message = $this->getNotificationMessage($payment) ?? $message;
if (!isset($status)) {
$status = $this->statusResolver->getOrderStatusByState($order, $state);
}
$order->setState($state);
$order->setStatus($status);
return __($message, $order->getBaseCurrency()->formatTxt($amount));
}
/**
* Sets order state and status.
*
* @param Order $order
* @param string $status
* @param string $state
* @return void
* @deprecated 100.1.9 Replaced by a StatusResolver class call.
*/
protected function setOrderStateAndStatus(Order $order, $status, $state)
{
if (!$status) {
$status = $order->getConfig()->getStateDefaultStatus($state);
}
$order->setState($state)->setStatus($status);
}
/**
* Returns payment notification message.
*
* @param OrderPaymentInterface $payment
* @return string|null
*/
private function getNotificationMessage(OrderPaymentInterface $payment): ?string
{
$extensionAttributes = $payment->getExtensionAttributes();
if ($extensionAttributes && $extensionAttributes->getNotificationMessage()) {
return $extensionAttributes->getNotificationMessage();
}
return null;
}
}
+155
View File
@@ -0,0 +1,155 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model\Product;
use Magento\Framework\Webapi\Rest\Request;
use Caratlane\NetSuite\Api\CreateProductInterface;
use Caratlane\NetSuite\Model\NetsuiteUpdateinvoicepdfFactory;
use Caratlane\NetSuite\Model\NetSuiteConstants;
use Caratlane\NetSuite\Helper\Logger;
use Caratlane\NetSuite\Helper\Data;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\App\ResourceConnection;
use Magento\Sales\Model\Order\Shipment;
class CreateProduct implements CreateProductInterface
{
/**
* @var \Magento\Framework\App\ResourceConnection
*/
private $resource;
/**
* @var \Magento\Sales\Model\Order\Shipment
*/
private $ordershipment;
/**
* @var \Caratlane\NetSuite\Helper\Logger
*/
protected $logger;
/**
* @var \Caratlane\NetSuite\Model\NetsuiteUpdateinvoicepdfFactory
*/
private $netsuiteupdateinvoicepdf;
/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
private $json;
/**
* @var \Caratlane\NetSuite\Helper\Data
*/
private $helper;
/**
* @var \Magento\Framework\Webapi\Rest\Request
*/
private $request;
/**
* @param ResourceConnection $resource
* @param Shipment $ordershipment
* @param Data $helper
* @param Json $json
* @param Logger $logger
* @param NetsuiteUpdateinvoicepdfFactory $netsuiteupdateinvoicepdf
* @param Request $request
*/
public function __construct(
Request $request,
ResourceConnection $resource,
Shipment $ordershipment,
Data $helper,
Json $json,
Logger $logger,
NetsuiteUpdateinvoicepdfFactory $netsuiteupdateinvoicepdf
) {
$this->request = $request;
$this->resource = $resource;
$this->ordershipment = $ordershipment;
$this->helper = $helper;
$this->json = $json;
$this->logger = $logger;
$this->netsuiteupdateinvoicepdf = $netsuiteupdateinvoicepdf;
}
public function createProduct()
{
if ($this->helper->getNetSuiteIsEnabled()) {
$this->logger->initLog(NetSuiteConstants::NETSUITE_CREATE_UPDATEPDF_LOG_FILENAME);
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('Create Product Started');
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('');
$postData = $this->request->getBodyParams();
try {
if ($postData['sku']) {
$this->logger->writeLog('Product Sku: '.$postData['sku']);
if (!$postData['sku'] || !$postData['name'] || !$postData['price']) {
$this->logger->writeLog('Please add required fields');
$responseData['success'] = false;
$responseData['message'] = "Please add required fields";
return [$responseData];
}
} else {
$this->logger->writeLog('Sku field can\'t be empty');
$responseData['success'] = false;
$responseData['message'] = "Sku field can't be empty";
}
} catch (Exception $e) {
$responseData['success'] = false;
$responseData['message'] = 'Exception : '.$e->getMessage();
$this->logger->writeLog('Exception: '.$e->getMessage());
}
$this->logger->writeLog('');
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('Create Product Stopped');
$this->logger->writeLog('----------------------------');
}
return [$responseData];
}
public function getordershipment(string $incrementshipId)
{
$shipId = 0;
try {
$shipment = $this->ordershipment->loadByIncrementId($incrementshipId);
$shipId = $shipment->getId();
return $shipId;
} catch (Exception $e) {
return $shipId;
}
}
}
@@ -0,0 +1,22 @@
<?php
/**
* @author 18th DigiTech Team
* @copyright Copyright (c) 2020 18th DigiTech (https://www.18thdigitech.com)
* @package Caratlane_NetSuite
*/
namespace Caratlane\NetSuite\Model\ResourceModel;
class NetSuite extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/*public function __construct(
\Magento\Framework\Model\ResourceModel\Db\Context $context
) {
parent::__construct($context);
}*/
protected function _construct()
{
$this->_init('netsuite_orders', 'entity_id'); //entity_id : Primary key of your database table
}
}
@@ -0,0 +1,28 @@
<?php
/**
* @author 18th DigiTech Team
* @copyright Copyright (c) 2020 18th DigiTech (https://www.18thdigitech.com)
* @package Caratlane_NetSuite
*/
namespace Caratlane\NetSuite\Model\ResourceModel\NetSuite;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'entity_id';
protected $_eventPrefix = 'netsuite_order_log_collection';
protected $_eventObject = 'netsuite_order_collection';
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(
\Caratlane\NetSuite\Model\NetSuite::class,
\Caratlane\NetSuite\Model\ResourceModel\NetSuite::class
);
}
}
@@ -0,0 +1,35 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class NetSuiteOrdersUpdate extends AbstractDb
{
/**
* Define main table
*/
protected function _construct()
{
$this->_init('netsuite_order_update', 'entity_id');
}
}
@@ -0,0 +1,38 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model\ResourceModel\NetSuiteOrdersUpdate;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init(
\Caratlane\NetSuite\Model\NetSuiteOrdersUpdate::class,
\Caratlane\NetSuite\Model\ResourceModel\NetSuiteOrdersUpdate::class
);
}
}
@@ -0,0 +1,35 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class NetsuiteShipments extends AbstractDb
{
/**
* Define main table
*/
protected function _construct()
{
$this->_init('netsuite_shipments', 'entity_id');
}
}
@@ -0,0 +1,38 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model\ResourceModel\NetsuiteShipments;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init(
\Caratlane\NetSuite\Model\NetsuiteShipments::class,
\Caratlane\NetSuite\Model\ResourceModel\NetsuiteShipments::class
);
}
}
@@ -0,0 +1,35 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class NetsuiteUpdateinvoicepdf extends AbstractDb
{
/**
* Define main table
*/
protected function _construct()
{
$this->_init('netsuite_invoice_pdf', 'entity_id');
}
}
@@ -0,0 +1,38 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model\ResourceModel\NetsuiteUpdateinvoicepdf;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init(
\Caratlane\NetSuite\Model\NetsuiteUpdateinvoicepdf::class,
\Caratlane\NetSuite\Model\ResourceModel\NetsuiteUpdateinvoicepdf::class
);
}
}
@@ -0,0 +1,519 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model\Shipment;
use Magento\Framework\Webapi\Rest\Request;
use Caratlane\NetSuite\Api\CreateShipmentInterface;
use Caratlane\NetSuite\Model\NetsuiteShipmentsFactory;
use Caratlane\NetSuite\Model\NetSuiteConstants;
use Caratlane\NetSuite\Helper\Logger;
use Caratlane\NetSuite\Helper\Data;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Sales\Model\Service\InvoiceService;
use Magento\Framework\DB\Transaction;
use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Shipping\Model\ShipmentNotifier;
use Magento\Sales\Model\Convert\Order;
use Magento\Sales\Model\Order\Shipment\TrackFactory;
use Magento\Framework\Serialize\Serializer\Json;
class CreateShipment implements CreateShipmentInterface
{
/**
* @var \Magento\Sales\Model\Order\Shipment\TrackFactory
*/
private $trackFactory;
/**
* @var \Magento\Framework\App\ResourceConnection
*/
private $resource;
/**
* @var \Magento\Sales\Model\Convert\Order
*/
private $convertOrder;
/**
* @var \Magento\Shipping\Model\ShipmentNotifier
*/
private $shipmentNotifier;
/**
* @var \Magento\Sales\Api\Data\OrderInterface
*/
private $orderInterface;
/**
* @var \Magento\Sales\Api\OrderRepositoryInterface
*/
private $orderRepository;
/**
* @var \Magento\Sales\Model\Service\InvoiceService
*/
private $invoiceService;
/**
* @var \Magento\Framework\DB\Transaction
*/
private $transaction;
/**
* @var \Magento\Sales\Model\Order\Email\Sender\InvoiceSender
*/
private $invoiceSender;
/**
* @var \Caratlane\NetSuite\Helper\Logger
*/
protected $logger;
/**
* @var \Caratlane\NetSuite\Model\NetsuiteShipmentsFactory
*/
private $netsuiteShipments;
/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
private $json;
/**
* @var \Caratlane\NetSuite\Helper\Data
*/
private $helper;
/**
* @var \Magento\Framework\Webapi\Rest\Request
*/
private $request;
/**
* @param TrackFactory $trackFactory
* @param ResourceConnection $resource
* @param Data $helper
* @param Json $json
* @param Order $convertOrder
* @param ShipmentNotifier $shipmentNotifier
* @param OrderInterface $orderInterface
* @param OrderRepositoryInterface $orderRepository
* @param InvoiceService $invoiceService
* @param InvoiceSender $invoiceSender
* @param Transaction $transaction
* @param Logger $logger
* @param NetsuiteShipmentsFactory $netsuiteShipments
* @param Request $request
*/
public function __construct(
Request $request,
ResourceConnection $resource,
Data $helper,
Json $json,
TrackFactory $trackFactory,
Order $convertOrder,
ShipmentNotifier $shipmentNotifier,
OrderRepositoryInterface $orderRepository,
InvoiceService $invoiceService,
InvoiceSender $invoiceSender,
Transaction $transaction,
OrderInterface $orderInterface,
Logger $logger,
NetsuiteShipmentsFactory $netsuiteShipments
) {
$this->request = $request;
$this->resource = $resource;
$this->helper = $helper;
$this->json = $json;
$this->trackFactory = $trackFactory;
$this->convertOrder = $convertOrder;
$this->shipmentNotifier = $shipmentNotifier;
$this->orderRepository = $orderRepository;
$this->invoiceService = $invoiceService;
$this->transaction = $transaction;
$this->invoiceSender = $invoiceSender;
$this->orderInterface = $orderInterface;
$this->logger = $logger;
$this->netsuiteShipments = $netsuiteShipments;
}
public function createNewShipment()
{
$responseData = [];
$responseData['success'] = NetSuiteConstants::NETSUITE_DEFAULT_ERROR_CODE;
$responseData['message'] = NetSuiteConstants::NETSUITE_DISABLE_MESSAGE;
if ($this->helper->getNetSuiteIsEnabled() && $this->helper->getNetsuiteCreateShipmentEnabled()) {
$this->logger->initLog(NetSuiteConstants::NETSUITE_CREATE_SHIPMENT_LOG_FILENAME);
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('Create Shipment Started');
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('');
$postData = $this->request->getBodyParams();
try {
if ($postData['ns_fulfillment_id']) {
$postDataarray = [];
$postDataarray['ns_fulfillment_id'] = $postData['ns_fulfillment_id'];
$postDataarray['ns_fulfillment_number'] = $postData['ns_fulfillment_number'];
$postDataarray['ns_order_id'] = $postData['ns_order_id'];
$postDataarray['magento_order_id'] = $postData['magento_order_id'];
$postDataarray['tracking_number'] = $postData['tracking_number'];
$postDataarray['shipping_carrier'] = $postData['shipping_carrier'];
$postDataarray['shipped_date'] = $postData['shipped_date'];
$postDataarray['delivery_status'] = $postData['delivery_status'];
foreach ($postDataarray as $key => $postvalue) {
if ($postvalue == "") {
$this->logger->writeLog('Please add required fields');
$responseData['success'] = false;
$responseData['message'] = "Please add required fields";
return [$responseData];
}
}
$incrementOrderId = $this->getOrderId($postData['magento_order_id']);
//echo $incrementOrderId; exit();
if ($incrementOrderId != "") {
$this->logger->writeLog('Magento Order Id: '.$postData['magento_order_id']);
$jsonData = $this->json->serialize($postData);
$order = $this->orderRepository->get($incrementOrderId);
if (!$order->canShip()) {
//Shipment have already created
$this->logger->writeLog('Shipment already created Or Not create a shipment');
$responseData['success'] = false;
$responseData['message'] = "Shipment already created Or Not create a shipment";
$netsuiteShipmentsModel = $this->netsuiteShipments->create();
$netsuiteShipmentsModel->setMagentoOrderId($postData['magento_order_id']);
$netsuiteShipmentsModel->setNetsuiteOrderId($postData['ns_order_id']);
$netsuiteShipmentsModel->setFulfillmentId($postData['ns_fulfillment_id']);
$netsuiteShipmentsModel->setFulfillmentNumber($postData['ns_fulfillment_number']);
$netsuiteShipmentsModel->setTrackingNumber($postData['tracking_number']);
$netsuiteShipmentsModel->setShippingCarrier($postData['shipping_carrier']);
$netsuiteShipmentsModel->setShippedDate($postData['shipped_date']);
$netsuiteShipmentsModel->setDeliveryStatus($postData['delivery_status']);
$netsuiteShipmentsModel->setStatus("failed");
$jsonData = $this->json->serialize($postData);
$netsuiteShipmentsModel->setJsonData($jsonData);
$netsuiteShipmentsModel->setMessages("Shipment already created Or Not create a shipment");
$netsuiteShipmentsModel->save();
} else {
$shipmentdata = $this->getCreateShipmentByOrderId($incrementOrderId, $jsonData);
$resposeShipmentflag = '';
$resposeShipmentflag = $this->updateNetsuiteShipments($shipmentdata, $postData);
if ($resposeShipmentflag) {
$shipids = explode(":", $shipmentdata);
$incrementId = $shipids[0];
$shipmentId = $shipids[1];
$responseData['success'] = true;
$responseData['message'] = "Shipment created successfully!";
$responseData['magento_shipment_id'] = $shipmentId;
$responseData['magento_shipment_no'] = $incrementId;
} else {
$responseData['success'] = false;
$responseData['message'] = "Not create shipment";
}
}
} else {
$this->logger->writeLog('Order id not found in system ='.$postData['magento_order_id']);
$responseData['success'] = false;
$responseData['message'] = "Order id not found in system";
}
} else {
$this->logger->writeLog('ns_fulfillment_id field can\'t be empty');
$responseData['success'] = false;
$responseData['message'] = "ns_fulfillment_id field can't be empty";
}
} catch (Exception $e) {
$responseData['success'] = false;
$responseData['message'] = 'Exception : '.$e->getMessage();
$this->logger->writeLog('Exception: '.$e->getMessage());
}
$this->logger->writeLog('');
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('Create Shipment Stopped');
$this->logger->writeLog('----------------------------');
}
return [$responseData];
}
private function updateNetsuiteShipments($shipmentdata, $postData)
{
$shipids = explode(":", $shipmentdata);
if ($shipids[0]) {
$incrementId = $shipids[0];
$shipmentId = $shipids[1];
$netsuiteShipmentsModel = $this->netsuiteShipments->create();
$netsuiteShipmentsModel->setMagentoOrderId($postData['magento_order_id']);
$netsuiteShipmentsModel->setNetsuiteOrderId($postData['ns_order_id']);
$netsuiteShipmentsModel->setFulfillmentId($postData['ns_fulfillment_id']);
$netsuiteShipmentsModel->setFulfillmentNumber($postData['ns_fulfillment_number']);
$netsuiteShipmentsModel->setTrackingNumber($postData['tracking_number']);
$netsuiteShipmentsModel->setShippingCarrier($postData['shipping_carrier']);
$netsuiteShipmentsModel->setShippedDate($postData['shipped_date']);
$netsuiteShipmentsModel->setShipmentId($incrementId);
$netsuiteShipmentsModel->setDeliveryStatus($postData['delivery_status']);
$netsuiteShipmentsModel->setStatus(NetSuiteConstants::NETSUITE_MIGRATION_STATUS);
$jsonData = $this->json->serialize($postData);
$netsuiteShipmentsModel->setJsonData($jsonData);
$shipsuccessmsg = NetSuiteConstants::NETSUITE_MIGRATION_SHIPMENT_SUCCESS_MESSAGE;
$netsuiteShipmentsModel->setMessages($shipsuccessmsg);
$netsuiteShipmentsModel->save();
$this->logger->writeLog('Shipment Id: '.$incrementId);
$this->logger->writeLog('Shipment created successfully');
return true;
} else {
$netsuiteShipmentsModel = $this->netsuiteShipments->create();
$netsuiteShipmentsModel->setMagentoOrderId($postData['magento_order_id']);
$netsuiteShipmentsModel->setNetsuiteOrderId($postData['ns_order_id']);
$netsuiteShipmentsModel->setFulfillmentId($postData['ns_fulfillment_id']);
$netsuiteShipmentsModel->setFulfillmentNumber($postData['ns_fulfillment_number']);
$netsuiteShipmentsModel->setTrackingNumber($postData['tracking_number']);
$netsuiteShipmentsModel->setShippingCarrier($postData['shipping_carrier']);
$netsuiteShipmentsModel->setShippedDate($postData['shipped_date']);
$netsuiteShipmentsModel->setDeliveryStatus($postData['delivery_status']);
$netsuiteShipmentsModel->setStatus("failed");
$jsonData = $this->json->serialize($postData);
$netsuiteShipmentsModel->setJsonData($jsonData);
$netsuiteShipmentsModel->setMessages("Cannot create shipment");
$netsuiteShipmentsModel->save();
$m_oid = $postData['magento_order_id'];
$logmsg = 'Cannot create shipment for Order increment id: ='.$m_oid;
$this->logger->writeLog($logmsg);
return false;
}
}
public function getCreateInvoiceByOrderId($orderId, $jsonData)
{
$order = $this->orderRepository->get($orderId);
if ($order->canInvoice()) {
$this->logger->initLog(NetSuiteConstants::NETSUITE_CREATE_SHIPMENT_LOG_FILENAME);
try {
$invoice = $this->invoiceService->prepareInvoice($order);
$invoice->register();
$invoice->save();
$transactionSave = $this->transaction->addObject($invoice)
->addObject($invoice->getOrder());
$transactionSave->save();
$this->invoiceSender->send($invoice);
$invoiceId = $invoice->getId();
$this->updateInvoiceCustomDetails($invoiceId, $jsonData);
//Send Invoice mail to customer
$order->addStatusHistoryComment(
__('Notified customer about invoice creation #%1.', $invoice->getId())
)
->setIsCustomerNotified(false)
->save();
$this->logger->writeLog('Invoice created successfully');
} catch (Exception $e) {
$this->logger->writeLog('Invoice not created');
}
}
}
public function getCustomShipQty($jsonData, $sku)
{
//$jsonData = (object)$this->json->unserialize($jsonData);
$jsonData = $this->json->unserialize($jsonData);
if (!empty($jsonData['items'])) {
foreach ($jsonData['items'] as $itesmData) {
$itesmData = (object)$itesmData;
if ($itesmData->item_sku == $sku) {
return $itesmData->item_qty;
}
}
}
return $itesmData = 0;
}
public function updateShipmentCustomDetails($shipmentId, $jsonData)
{
//$jsonData = (object)$this->json->unserialize($jsonData);
$jsonData = $this->json->unserialize($jsonData);
$connection = $this->resource->getConnection();
$data['ns_fulfillment_id'] = $jsonData['ns_fulfillment_id'];
$data['ns_fulfillment_number'] = $jsonData['ns_fulfillment_number'];
$data['ns_tracking_number'] = $jsonData['tracking_number'];
$data['ns_delivery_status'] = $jsonData['delivery_status'];
$data['ns_shipping_carrier'] = $jsonData['shipping_carrier'];
$data['ns_shipped_date'] = date("Y-m-d h:i:sa");
$where = ['entity_id = ?' => (int)$shipmentId];
/* update sales_shipment_grid */
$tableName = $connection->getTableName("sales_shipment_grid");
$connection->update($tableName, $data, $where);
/* update sales_shipment */
$tableName = $connection->getTableName("sales_shipment");
$connection->update($tableName, $data, $where);
/* update sales_shipment_item */
$itemarray = $jsonData['items'];
if (!empty($itemarray)) {
foreach ($itemarray as $key => $shipitem) {
$dataitem = [];
$itemconnection = $this->resource->getConnection();
$dataitem['ns_expected_delivery_from_date'] = $shipitem['expected_delivery_from_date'];
$dataitem['ns_expected_delivery_to_date'] = $shipitem['expected_delivery_to_date'];
$dataitem['ns_serial_no'] = $shipitem['serial_no'];
$dataitem['ns_certificate'] = $shipitem['certificate'];
$itemwhere = ['parent_id = ?' => (int)$shipmentId,'sku = ?' => $shipitem['item_sku']];
$itemtableName = $itemconnection->getTableName("sales_shipment_item");
$itemconnection->update($itemtableName, $dataitem, $itemwhere);
$this->logger->writeLog('Shipment Item Sku: '.$shipitem['item_sku']);
$this->logger->writeLog('Shipment Item Qty: '.$shipitem['item_qty']);
}
}
}
public function updateInvoiceCustomDetails($invoiceId, $jsonData)
{
$jsonData = (object)$this->json->unserialize($jsonData);
$connection = $this->resource->getConnection();
$data['ns_fulfillment_id'] = $jsonData->fulfillment_id;
$data['ns_fulfillment_number'] = $jsonData->fulfillment_number;
$where = ['entity_id = ?' => (int)$invoiceId];
/* update sales_invoice_grid */
$tableName = $connection->getTableName("sales_invoice_grid");
$connection->update($tableName, $data, $where);
/* update sales_invoice */
$tableName = $connection->getTableName("sales_invoice");
$connection->update($tableName, $data, $where);
}
public function getCreateShipmentByOrderId($orderId, $jsonData)
{
$order = $this->orderRepository->get($orderId);
// check if it's possible to ship the items
if ($order->canShip()) {
$this->logger->initLog(NetSuiteConstants::NETSUITE_CREATE_SHIPMENT_LOG_FILENAME);
$shipment = $this->convertOrder->toShipment($order);
foreach ($order->getAllItems() as $orderItem) {
// Check if the order item has Quantity to ship or is virtual
if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
continue;
}
$getshipCustomQty = $this->getCustomShipQty($jsonData, $orderItem->getSku());
$qtyShipped = $orderItem->getQtyToShip();
if (($getshipCustomQty > 0 ) && ($getshipCustomQty <= $qtyShipped )) {
// Create Shipment Item with Quantity
$shipmentItem = $this->convertOrder->itemToShipmentItem($orderItem)->setQty($getshipCustomQty);
// Add Shipment Item to Shipment
$shipment->addItem($shipmentItem);
}
}
$track = $this->setOrderTrackFactoryData($jsonData);
$shipment->addTrack($track);
// Register Shipment
$shipment->register();
$shipment->getOrder()->setIsInProcess(true);
try {
$shipment->getExtensionAttributes()->setSourceCode('default');
// Save created Shipment and Order
$shipment->save();
$shipmentId = $shipment->getId();
$incrementId = $shipment->getIncrementId();
$shipment->getOrder()->save();
// send shipping confirmation e-mail to customer
$this->shipmentNotifier->notify($shipment);
$this->updateShipmentCustomDetails($shipmentId, $jsonData);
return $incrementId.':'.$shipmentId;
} catch (\Exception $e) {
$this->logger->writeLog($e->getMessage());
$this->logger->writeLog('Fail to created Shipment');
}
}
}
public function setOrderTrackFactoryData($jsonData)
{
//$jsonData = (object)$this->json->unserialize($jsonData);
$jsonData = $this->json->unserialize($jsonData);
$track = $this->trackFactory->create();
$track->setTrackNumber($jsonData['tracking_number']);
$track->setCarrierCode(NetSuiteConstants::NETSUITE_TRACKING_CODE);
$track->setTitle($jsonData['shipping_carrier']);
return $track;
}
public function getOrderId(string $incrementOrderId)
{
$orderId = 0;
try {
$orderInfo = $this->orderInterface->loadByIncrementId($incrementOrderId);
$orderId = $orderInfo->getId();
return $orderId;
} catch (Exception $e) {
return $orderId;
}
}
}
+207
View File
@@ -0,0 +1,207 @@
<?php
/**
* Caratlane
*
* NOTICE OF LICENSE
*
* This source file is subject to the Caratlane.com license that is
* available through the world-wide-web at this URL:
* https://www.Caratlane.com/LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to any file if you wish to upgrade this extension
* version in the future.
*
* @category Caratlane
* @package Caratlane_NetSuite
* @copyright Copyright (c) Caratlane (https://www.Caratlane.com/)
* @license https://www.Caratlane.com/LICENSE.txt
*/
namespace Caratlane\NetSuite\Model\Shipment;
use Magento\Framework\Webapi\Rest\Request;
use Caratlane\NetSuite\Api\UpdateInvoicePdfInterface;
use Caratlane\NetSuite\Model\NetsuiteUpdateinvoicepdfFactory;
use Caratlane\NetSuite\Model\NetSuiteConstants;
use Caratlane\NetSuite\Helper\Logger;
use Caratlane\NetSuite\Helper\Data;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\App\ResourceConnection;
use Magento\Sales\Model\Order\Shipment;
class UpdatePdf implements UpdateInvoicePdfInterface
{
/**
* @var \Magento\Framework\App\ResourceConnection
*/
private $resource;
/**
* @var \Magento\Sales\Model\Order\Shipment
*/
private $ordershipment;
/**
* @var \Caratlane\NetSuite\Helper\Logger
*/
protected $logger;
/**
* @var \Caratlane\NetSuite\Model\NetsuiteUpdateinvoicepdfFactory
*/
private $netsuiteupdateinvoicepdf;
/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
private $json;
/**
* @var \Caratlane\NetSuite\Helper\Data
*/
private $helper;
/**
* @var \Magento\Framework\Webapi\Rest\Request
*/
private $request;
/**
* @param ResourceConnection $resource
* @param Shipment $ordershipment
* @param Data $helper
* @param Json $json
* @param Logger $logger
* @param NetsuiteUpdateinvoicepdfFactory $netsuiteupdateinvoicepdf
* @param Request $request
*/
public function __construct(
Request $request,
ResourceConnection $resource,
Shipment $ordershipment,
Data $helper,
Json $json,
Logger $logger,
NetsuiteUpdateinvoicepdfFactory $netsuiteupdateinvoicepdf
) {
$this->request = $request;
$this->resource = $resource;
$this->ordershipment = $ordershipment;
$this->helper = $helper;
$this->json = $json;
$this->logger = $logger;
$this->netsuiteupdateinvoicepdf = $netsuiteupdateinvoicepdf;
}
public function updateInvoicePdf()
{
$responseData = [];
$responseData['success'] = NetSuiteConstants::NETSUITE_DEFAULT_ERROR_CODE;
$responseData['message'] = NetSuiteConstants::NETSUITE_DISABLE_MESSAGE;
if ($this->helper->getNetSuiteIsEnabled() && $this->helper->getNetsuiteUpdateInvoicepdfEnabled()) {
$this->logger->initLog(NetSuiteConstants::NETSUITE_CREATE_UPDATEPDF_LOG_FILENAME);
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('Update invoice pdf Started');
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('');
$postData = $this->request->getBodyParams();
try {
if ($postData['magento_shipment_id']) {
$this->logger->writeLog('Magento Shipment Id: '.$postData['magento_shipment_id']);
$postDataarray = [];
$postDataarray['ns_fulfillment_id'] = $postData['ns_fulfillment_id'];
$postDataarray['ns_fulfillment_number'] = $postData['ns_fulfillment_number'];
$postDataarray['magento_shipment_id'] = $postData['magento_shipment_id'];
$postDataarray['invoice_url'] = $postData['invoice_url'];
foreach ($postDataarray as $key => $postvalue) {
if ($postvalue == "") {
$this->logger->writeLog('Please add required fields');
$responseData['success'] = false;
$responseData['message'] = "Please add required fields";
return [$responseData];
}
}
$getshipmentid = $this->getordershipment($postData['magento_shipment_id']);
if ($getshipmentid != "") {
$netsuiteShipmentsModel = $this->netsuiteupdateinvoicepdf->create();
$netsuiteShipmentsModel->setMagentoShipmentId($postData['magento_shipment_id']);
$netsuiteShipmentsModel->setFulfillmentId($postData['ns_fulfillment_id']);
$netsuiteShipmentsModel->setFulfillmentNumber($postData['ns_fulfillment_number']);
$netsuiteShipmentsModel->setInvoiceUrl($postData['invoice_url']);
$netsuiteShipmentsModel->setStatus("completed");
$jsonData = $this->json->serialize($postData);
$netsuiteShipmentsModel->setJsonData($jsonData);
$netsuiteShipmentsModel->setMessages("Update Invoice PDF successfully.");
$netsuiteShipmentsModel->save();
//update data for shipment table
$connection = $this->resource->getConnection();
$data = [];
$data['ns_invoice_url'] = $postData['invoice_url'];
$where = ['increment_id = ?' => $postData['magento_shipment_id']];
/* update sales_shipment_grid */
$tableName = $connection->getTableName("sales_shipment_grid");
$connection->update($tableName, $data, $where);
/* update sales_shipment */
$tableName = $connection->getTableName("sales_shipment");
$connection->update($tableName, $data, $where);
$this->logger->writeLog('Invoice URL updated successfully');
$responseData['success'] = true;
$responseData['message'] = "Invoice URL updated successfully";
$responseData['magento_shipment_id'] = $postData['magento_shipment_id'];
} else {
$this->logger->writeLog('Shipment id not found in system ='.$postData['magento_shipment_id']);
$responseData['success'] = false;
$responseData['message'] = "Shipment id not found in system";
}
} else {
$this->logger->writeLog('magento_shipment_id field can\'t be empty');
$responseData['success'] = false;
$responseData['message'] = "magento_shipment_id field can't be empty";
}
} catch (Exception $e) {
$responseData['success'] = false;
$responseData['message'] = 'Exception : '.$e->getMessage();
$this->logger->writeLog('Exception: '.$e->getMessage());
}
$this->logger->writeLog('');
$this->logger->writeLog('----------------------------');
$this->logger->writeLog('Update invoice pdf Stopped');
$this->logger->writeLog('----------------------------');
}
return [$responseData];
}
public function getordershipment(string $incrementshipId)
{
$shipId = 0;
try {
$shipment = $this->ordershipment->loadByIncrementId($incrementshipId);
$shipId = $shipment->getId();
return $shipId;
} catch (Exception $e) {
return $shipId;
}
}
}