Last active
September 29, 2023 05:43
-
-
Save sandipklevu/91b8a4e2f94745e1132b8e8026c94c35 to your computer and use it in GitHub Desktop.
Can place this script on `pub` folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Klevu\Search\Model\System\Config\Source\Order\Ip as OrderIP; | |
use Magento\Framework\App\Bootstrap; | |
use Magento\Framework\App\Filesystem\DirectoryList; | |
use Magento\Framework\Exception\NoSuchEntityException; | |
if (PHP_SAPI !== 'cli') { | |
echo 'klevu-sales-tracking must be run as a CLI application'; | |
exit(1); | |
} | |
try { | |
require __DIR__ . '/../app/bootstrap.php'; | |
$bootstrap = Bootstrap::create(BP, $_SERVER); | |
$objectManager = $bootstrap->getObjectManager(); | |
/** @var \Magento\Store\Model\StoreManagerInterface $storeManager */ | |
$storeManager = $objectManager->get(\Magento\Store\Model\StoreManagerInterface::class); | |
} catch (\Exception $e) { | |
echo 'Autoload error: ' . $e->getMessage(); | |
exit(1); | |
} | |
$storeObject = ''; | |
$options = getopt("i::s::e::s::p:", | |
["is_to_send::", "start_date::", "end_date::", "store_code::", "page_size::"] | |
); | |
if (false === $options || !is_array($options)) { | |
print "There was a problem reading in the options.\n\n"; | |
exit(1); | |
} | |
$isToSend = $options['is_to_send'] ?? null; | |
$startDate = $options['start_date'] ?? null; | |
if (!$startDate) { | |
$startDate = '2021-04-06'; | |
} | |
$startDate .= ' 00:00:00'; | |
$endDate = $options['end_date'] ?? null; | |
if (!$endDate) { | |
$endDate = '2023-09-11'; | |
} | |
$endDate .= ' 23:59:59'; | |
$store_id = $options['store_code'] ?? 1; | |
$orderSize = (int)$options['page_size'] ?? null; | |
if (!$orderSize) { | |
$orderSize = 5; | |
} | |
//Resetting the page size limit to avoid load issues | |
if ($orderSize > 100) { | |
$orderSize = 100; | |
} | |
$frameworkModelResource = $objectManager->get( | |
'Magento\Framework\App\ResourceConnection' | |
); | |
$orderCollectionFactory = $objectManager->create( | |
'Magento\Sales\Model\ResourceModel\Order\CollectionFactory' | |
); | |
$directoryList = $objectManager->get('Magento\Framework\Filesystem\DirectoryList'); | |
$orderItemDataProvider = $objectManager->get( | |
'\Klevu\Search\Api\Provider\Sync\Order\Item\DataProviderInterface' | |
); | |
$itemDataConverterProvider = $objectManager->get( | |
'\Klevu\Search\Service\Convertor\OrderSyncItemDataConvertor' | |
); | |
$modelOrderItemFactory = $objectManager->get('\Magento\Sales\Model\Order\ItemFactory'); | |
$dataObject = $objectManager->get('\Magento\Framework\DataObject'); | |
$configHelper = $objectManager->get('\Klevu\Search\Helper\Config'); | |
$klevuDataHelper = $objectManager->get('\Klevu\Search\Helper\Data'); | |
$fileDriver = $objectManager->get('Magento\Framework\Filesystem\Driver\File'); | |
$klevuProductTracking = $objectManager->get( | |
'\Klevu\Search\Model\Api\Action\Producttracking' | |
); | |
$filesystem = $objectManager->get('Magento\Framework\Filesystem'); | |
try { | |
$storeObject = $storeManager->getStore($store_id); | |
} catch (NoSuchEntityException $e) { | |
echo 'Store not found:' . $e->getMessage() . PHP_EOL; | |
exit; | |
} | |
try { | |
$storeManager->setCurrentStore($storeObject); | |
} catch (\Exception $e) { | |
echo 'Store not able to set to current store:' . $e->getMessage() . PHP_EOL; | |
exit; | |
} | |
$lockFileName = 'klevu_lock_sales.lock'; | |
$lockFileRunningState = 'klevu_old_sales_running_index.lock'; | |
$varDir = $directoryList->getPath(DirectoryList::VAR_DIR); | |
$lockFileFullPath = $varDir . "/" . $lockFileName; | |
try { | |
/** @var Magento\Framework\App\State $appState */ | |
$state = $objectManager->get('Magento\Framework\App\State'); | |
if (file_exists($lockFileFullPath)) { | |
unlink($lockFileFullPath); | |
} | |
$state->setAreaCode('frontend'); | |
} catch (\Exception $e) { | |
echo 'Exception frontend error:' . $e->getMessage() . PHP_EOL; | |
$existingAreaCode = $this->appState->getAreaCode(); | |
if ('frontend' !== $existingAreaCode) { | |
touch($lockFileFullPath); | |
} | |
} | |
try { | |
$pub = $directoryList->getPath(DirectoryList::PUB); | |
$varDirectory = $filesystem->getDirectoryWrite( | |
DirectoryList::VAR_DIR | |
); | |
$storeLockFile = $varDir . "/" . $lockFileRunningState; | |
if (file_exists($storeLockFile)) { | |
echo 'Process is running since' . fileatime($storeLockFile) . PHP_EOL; | |
return; | |
} | |
fopen($storeLockFile, 'w'); | |
$websiteId = $storeObject->getWebsiteId(); | |
$currentStoreId = $storeObject->getId(); | |
$colWidths = [15, 25, 20, 150]; | |
$divider = sprintf( | |
'+%s+%s+%s+%s+', | |
str_repeat('-', $colWidths[0]), | |
str_repeat('-', $colWidths[1]), | |
str_repeat('-', $colWidths[2]), | |
str_repeat('-', $colWidths[3]) | |
); | |
$smallDivider = sprintf( | |
'+%s+%s+', | |
str_repeat('-', $colWidths[0]), | |
str_repeat('-', $colWidths[1]) | |
); | |
echo $smallDivider . PHP_EOL; | |
echo "STORE SUMMARY" . PHP_EOL; | |
echo $smallDivider . PHP_EOL; | |
$configuredOrderIP = $configHelper->getConfiguredOrderIP($store_id); | |
$jsApiKey = $configHelper->getJsApiKey($store_id); | |
$fileName = 'lastOrderIncrementId.txt'; | |
$incrementId = null; | |
if ($varDirectory->isExist($fileName)) { | |
$incrementId = $varDirectory->readFile( | |
$fileName | |
); | |
} else { | |
echo 'During reading file not found: ' . $fileName . PHP_EOL; | |
} | |
$finalOptions = [ | |
'Store ID' => $store_id, | |
'Website ID' => $websiteId, | |
'IP Column' => $configuredOrderIP, | |
'JS Api Key' => $jsApiKey, | |
'Last Order ID' => $incrementId, | |
]; | |
foreach ($finalOptions as $key => $val) { | |
echo sprintf( | |
'|%s|%s|', | |
str_pad(' ' . $key, $colWidths[0], ' ', STR_PAD_RIGHT), | |
str_pad(' ' . $val, $colWidths[1], ' ', STR_PAD_RIGHT) | |
) . PHP_EOL; | |
} | |
echo $smallDivider . PHP_EOL; | |
echo "ARGUMENTS SUMMARY" . PHP_EOL; | |
echo $smallDivider . PHP_EOL; | |
foreach ($options as $key => $val) { | |
echo sprintf( | |
'|%s|%s|', | |
str_pad(' ' . $key, $colWidths[0], ' ', STR_PAD_RIGHT), | |
str_pad(' ' . $val, $colWidths[1], ' ', STR_PAD_RIGHT) | |
) . PHP_EOL; | |
} | |
echo $smallDivider . PHP_EOL; | |
echo "FINAL VALUES SUMMARY" . PHP_EOL; | |
echo $smallDivider . PHP_EOL; | |
$finalOptions = [ | |
'IsToSend' => $isToSend, | |
'Start Date' => $startDate, | |
'End Date' => $endDate, | |
'StoreId' => $store_id, | |
'No Of Orders' => $orderSize, | |
]; | |
foreach ($finalOptions as $key => $val) { | |
echo sprintf( | |
'|%s|%s|', | |
str_pad(' ' . $key, $colWidths[0], ' ', STR_PAD_RIGHT), | |
str_pad(' ' . $val, $colWidths[1], ' ', STR_PAD_RIGHT) | |
) . PHP_EOL; | |
} | |
echo $smallDivider . PHP_EOL; | |
$orderCollection = $orderCollectionFactory->create() | |
->addAttributeToSelect('increment_id') | |
->addAttributeToSelect('entity_id') | |
->addAttributeToSelect('created_at') | |
->addAttributeToSelect(OrderIP::ORDER_REMOTE_IP) | |
->addAttributeToSelect(OrderIP::ORDER_X_FORWARDED_FOR) | |
->addAttributeToFilter('main_table.created_at', ['from' => $startDate, 'to' => $endDate]); | |
if ($currentStoreId) { | |
$orderCollection->addAttributeToFilter('main_table.store_id', $currentStoreId); | |
} | |
if (null !== $incrementId) { | |
$orderCollection->addAttributeToFilter('main_table.increment_id', ['gt' => $incrementId]); | |
} | |
$orderCollection->setCurPage(1); | |
//Passing limit on getSelect | |
$orderCollection->getSelect()->limit($orderSize); | |
echo "QUERY: " . PHP_EOL . $orderCollection->getSelect() . PHP_EOL; | |
echo $divider . PHP_EOL; | |
echo $divider . PHP_EOL; | |
echo sprintf( | |
'|%s|%s|', | |
str_pad(' OrderId ', $colWidths[0], ' ', STR_PAD_RIGHT), | |
str_pad(' OrderDate ', $colWidths[1], ' ', STR_PAD_RIGHT) | |
); | |
if ($isToSend) { | |
echo sprintf( | |
'|%s|', | |
str_pad(' OrderStatus ', $colWidths[2], ' ', STR_PAD_RIGHT) | |
); | |
} | |
echo sprintf( | |
'%s|', | |
str_pad(' OrderData ', $colWidths[3], ' ', STR_PAD_RIGHT) | |
) . PHP_EOL; | |
/** @var \Magento\Sales\Model\Order $order */ | |
foreach ($orderCollection as $order) { | |
if (!$order) { | |
echo 'Order not valid: ' . PHP_EOL; | |
continue; | |
} | |
echo $divider . PHP_EOL; | |
$orderItems = $order->getAllItems(); | |
/** @var \Magento\Sales\Model\Order\Item $item */ | |
foreach ($orderItems as $orderItemKey => $item) { | |
//Will skip if order item is children | |
if ($item->getParentItemId()) { | |
continue; | |
} | |
$orderItemData = $orderItemDataProvider->getData($item); | |
try { | |
$parameters = $itemDataConverterProvider->convert($orderItemData); | |
echo sprintf( | |
'|%s|%s|', | |
str_pad(' ' . $order->getIncrementId(), | |
$colWidths[0], | |
' ', | |
STR_PAD_RIGHT | |
), | |
str_pad(' ' . $order->getCreatedAt() . $item->getOrderId() . ' ', $colWidths[1], ' ', STR_PAD_RIGHT) | |
); | |
$parameters['klevu_apiKey'] = $jsApiKey; | |
if (array_key_exists( | |
'klevu_checkoutDate', | |
$parameters | |
) | |
&& empty($parameters['klevu_checkoutDate'])) { | |
$parameters['klevu_checkoutDate'] = strtotime($order->getCreatedAt()) . '000'; | |
$parameters['klevu_orderDate'] = $order->getCreatedAt(); | |
} | |
$shopperIP = getOrderIP( | |
$configuredOrderIP, | |
$order | |
); | |
if (!$shopperIP) { | |
echo sprintf( | |
'Order IP address not found for given order ID: %s', | |
$item->getOrderId() | |
) . PHP_EOL; | |
continue; | |
} | |
$parameters['klevu_shopperIP'] = $shopperIP; | |
unset($parameters['klevu_productPosition']); | |
unset($parameters['klevu_orderId']); | |
unset($parameters['klevu_orderLineId']); | |
unset($parameters['klevu_storeTimezone']); | |
unset($parameters['klevu_orderDate']); | |
unset($parameters['klevu_emailId']); | |
unset($parameters['klevu_sessionId']); | |
unset($parameters['klevu_clientIp']); | |
if ($isToSend) { | |
$store = $storeManager->getStore($item->getStoreId()); | |
$klevuProductTracking->setStore($store); | |
$store = $storeManager->getStore($item->getStoreId()); | |
$klevuProductTracking->setStore($store); | |
$response = $klevuProductTracking->execute($parameters); | |
if ($response) { | |
echo sprintf( | |
'%s|', | |
str_pad(' SUCCESS ', | |
$colWidths[2], | |
' ', | |
STR_PAD_RIGHT | |
), | |
); | |
} else { | |
echo sprintf( | |
'%s|', | |
str_pad(' FAILED ', | |
$colWidths[2], | |
' ', | |
STR_PAD_RIGHT | |
), | |
); | |
} | |
} | |
$parametersString = print_r($parameters, true); | |
echo sprintf( | |
'%s', | |
str_pad(' ' . str_replace("\n", "", $parametersString) . ' ', | |
$colWidths[3], | |
' ', | |
STR_PAD_RIGHT | |
) . PHP_EOL | |
); | |
echo $divider . PHP_EOL; | |
} catch (InvalidArgumentException $e) { | |
echo 'Order Invalid Argument Exception: ' . $e->getMessage() . PHP_EOL; | |
continue; | |
} catch (\Exception $e) { | |
echo 'Order Exception thrown: ' . $e->getMessage() . PHP_EOL; | |
continue; | |
} | |
} | |
try { | |
$varDirectory->writeFile( | |
$fileName, | |
$order->getIncrementId() | |
); | |
} catch (\Magento\Framework\Exception\FileSystemException $e) { | |
echo 'OrderID write exception.' . $e->getMessage() . PHP_EOL; | |
} | |
} | |
echo $divider . PHP_EOL; | |
if (file_exists($storeLockFile)) { | |
unlink($storeLockFile); | |
} | |
} catch (\Magento\Framework\Exception\FileSystemException $e) { | |
echo 'FileSystemException thrown.' . $e->getMessage() . PHP_EOL; | |
} catch (\Exception $e) { | |
echo 'Exception thrown.' . $e->getMessage() . PHP_EOL; | |
} | |
/** | |
* @param $configuredOrderIP | |
* @param $order | |
* | |
* @return mixed | |
*/ | |
function getOrderIP( | |
$configuredOrderIP, | |
$order | |
) { | |
switch ($configuredOrderIP) { | |
case OrderIP::ORDER_X_FORWARDED_FOR: | |
$ipColumn = OrderIP::ORDER_X_FORWARDED_FOR; | |
break; | |
default: | |
$ipColumn = OrderIP::ORDER_REMOTE_IP; | |
break; | |
} | |
$orderIps = $order->getData($ipColumn); | |
if (!$orderIps) { | |
if ($ipColumn === OrderIP::ORDER_REMOTE_IP) { | |
$ipColumn = OrderIP::ORDER_X_FORWARDED_FOR; | |
} else { | |
$ipColumn = OrderIP::ORDER_REMOTE_IP; | |
} | |
$orderIps = $order->getData($ipColumn); | |
echo ' Fallback IP : ' . $ipColumn . ' VALUE: ' . $orderIps; | |
} | |
if (!$orderIps) { | |
echo ' NO value found for any IP Column |' . PHP_EOL; | |
return null; | |
} | |
if (str_contains($orderIps, ",")) { | |
$trimOrderIP = array_map( | |
'trim', | |
explode(",", $orderIps) | |
); | |
return array_shift($trimOrderIP); | |
} | |
echo ' IP Address: ' . $orderIps . ' | '; | |
return $orderIps; | |
} | |
echo "Search led conversion completed " . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you please follow the below steps and share the file(s) with us?
It's all object manager-based, so won't need a recompile of the site to run.
The file can be placed in the accessible directory i.e.
pub
orvar
orbin
or any manually created directory.Once the file is added, please run the below command
Where
is_to_send
may have a 0 or 1 value. The default value is 0.Where
start_date
is the Start date, the format should be YYYY-MM-DD, default value is 2021-04-06Where
end_date
is the End date, the format should be YYYY-MM-DD, default value is 2023-09-11Where
store_code
is the Magento store code for the store, the default value is 1 (default)Where
page_size
is the number of orders, default 10-100 maxAfter executing the above command, please share the below path file(s) with us.