Upload inventory and update inventory from Different server Magento2

Step 1 : create one file "uploadinventory.php" and write this code
<?php
ini_set('display_errors', 1);
ini_set('max_execution_time', 300000);
ini_set("memory_limit", "-1");
set_time_limit(0);
error_reporting(E_ALL);
require '/srv/users/serverpilot/apps/Root/public/app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
// Inventory Upload code
$start_time = date("j-F-Y, g:i a");
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$ftp_server = "xxxxxxx";
$ftp_user_name = "xxxx";
$ftp_user_pass = "xxx";
$conn_id = ftp_connect($ftp_server);
ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, TRUE);
$date = date("dmY");
$sfilename = 'A068_MGF_'.$date.'.csv';
$server_file = $sfilename;
$local_file = "/srv/users/serverpilot/apps/Root/public/pub/media/inventory/inventory.csv";
$fp_local = fopen($local_file, "w+");
$final_file_name = "/srv/users/serverpilot/apps/Root/public/pub/media/inventory/inventoryfile.csv";
if (file_exists($final_file_name)) {
    unlink($final_file_name);
}
if (ftp_fget($conn_id, $fp_local, $server_file, FTP_BINARY)) {
    fclose($fp_local);
    
    $message = "File created (inventoryfile.csv) successfully through cron";
    $end_time = date("j-F-Y, g:i a");
} else {
    $message = "Error in creating inventory file through cron job\n";
    $end_time = date("j-F-Y, g:i a");
}
ftp_close($conn_id);
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/uploaded_INVENTORY.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info($message . "start time = " . $start_time . " end time = " . $end_time);
?>


Step 2 : After the creation of uploadinventory.php file run it and it will automatically create one csv file in your FTP ('pub/media/inventory/inventory.csv')

Step 3 : Create another file "updateinventory.php"


<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ini_set('max_execution_time', 300000);
ini_set("memory_limit", "-1");
set_time_limit(0);
use Magento\Framework\App\Bootstrap;
require '/srv/users/serverpilot/apps/Root/public/app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$start_time = "";
$end_time = "";
try {
    // Inventory Updation code
    $start_time = date("j-F-Y, g:i a");
    $skus = array();
    $invfile = "/srv/users/serverpilot/apps/Root/public/pub/media/inventory/inventory.csv";
    $file = fopen($invfile, 'r');

    while (($line = fgetcsv($file)) !== FALSE) {
        $skus[$line[1]] = $line[10];
    }
    fclose($file);
    $products_count = 0;
    $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
    $productCollection->setFlag('has_stock_status_filter', true);
    $sp_collection = $productCollection->addAttributeToSelect('*')->addAttributeToFilter('type_id', \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)->load();
    foreach ($sp_collection as $simple_products) {
        if (array_key_exists($simple_products->getArticleCode(), $skus)) {
            $inventory = (int)$skus[$simple_products->getArticleCode() ];
            $product = $objectManager->get('Magento\Catalog\Model\Product')->load($simple_products->getId());
            $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
            $connection = $resource->getConnection();
            $tableName = $resource->getTableName('cataloginventory_stock_item');
            if ($inventory > 0) {
                $is_in_stock = 1;
            } else {
                $is_in_stock = 0;
            }
            $sql = 'Update ' . $tableName . ' Set qty = "' . $inventory . '", is_in_stock ="' . $is_in_stock . '" where product_id = "' . $simple_products->getId() . '"';
            echo "<p>" . $simple_products->getId() . "\t" . $inventory . "</p>";
            $connection->query($sql);
            $products_count++;
        } else {
            continue;
        }
    }
    $indexerFactory = $objectManager->get('Magento\Indexer\Model\IndexerFactory');
    $indexerIds = array('catalog_category_product', 'catalog_product_category', 'catalog_product_price', 'catalog_product_attribute', 'cataloginventory_stock', 'catalogrule_product', 'catalogsearch_fulltext',);
    foreach ($indexerIds as $indexerId) {
        echo " create index: " . $indexerId . "\n";
        $indexer = $indexerFactory->create();
        $indexer->load($indexerId);
        $indexer->reindexAll();
    }
    $end_time = date("j-F-Y, g:i a");
    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/updated_INVENTORY.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);
    $logger->info($products_count . " in stock Products inventory updated start time = " . $start_time . " end time = " . $end_time);
}
catch(\Exception $e) {
    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/updated_INVENTORY.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);
    $logger->info("There is some error in updating inventory, error message is: " . $e->getMessage() . ", start time is: " . $start_time . " and end time is: " . $end_time);
}
?>


Step 4 : After the creation of updateinventory.php file you can run it. Once it will successfully run your inventory has been updated please check and confirm. 

Comments