Spamworldpro Mini Shell
Spamworldpro


Server : Apache
System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64
User : corals ( 1002)
PHP Version : 7.4.33
Disable Function : exec,passthru,shell_exec,system
Directory :  /home/corals/cartforge.co/scripts/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/corals/cartforge.co/scripts/import_products.php
<?php

use Magento\Catalog\Api\Data\ProductInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Catalog\Model\CategoryRepository;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory as OptionsFactory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\CouldNotSaveException;

try {
    require_once '../app/bootstrap.php';
} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}

ini_set('display_errors', 1);
error_reporting(E_ALL);

try {
    $dbHost = '127.0.0.1';
    $dbName = 'cartfroge_import';
    $dbUser = 'root';
    $dbPassword = 'root1234';

// Create a new database connection
    try {
        $customConnection = new \Zend_Db_Adapter_Pdo_Mysql([
            'host' => $dbHost,
            'dbname' => $dbName,
            'username' => $dbUser,
            'password' => $dbPassword,
        ]);
        $customConnection->query("SET NAMES utf8");
    } catch (\Exception $e) {
        echo "Error connecting to custom database: " . $e->getMessage() . "\n";
        exit;
    }

    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('Magento\Framework\App\State');
    $appState->setAreaCode('frontend');


    /** @var ResourceConnection $resource */
    $resource = $objectManager->get(ResourceConnection::class);
    $connection = $resource->getConnection();

    /** @var ProductRepositoryInterface $productRepository */
    $productRepository = $objectManager->get(ProductRepositoryInterface::class);

    /** @var ProductInterfaceFactory $productFactory */
    $productFactory = $objectManager->get(ProductInterfaceFactory::class);

    /** @var Configurable $configurableType */
    $configurableType = $objectManager->get(Configurable::class);

    /** @var OptionsFactory $optionsFactory */
    $optionsFactory = $objectManager->get(OptionsFactory::class);

    /** @var CategoryFactory $categoryFactory */
    $categoryFactory = $objectManager->get(CategoryFactory::class);

    $eavSetup = $objectManager->get(\Magento\Eav\Setup\EavSetup::class);
    $attributeFactory = $objectManager->get(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);

    $fileSystem = $objectManager->get('Magento\Framework\Filesystem\Io\File');
    $directoryList = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList');


    $eavConfig = $objectManager->get('\Magento\Eav\Model\Config');
    $color_attribute = $eavConfig->getAttribute('catalog_product', 'color');
    $size_attribute = $eavConfig->getAttribute('catalog_product', 'size');
    $fit_attribute = $eavConfig->getAttribute('catalog_product', 'fit');


    $colors = $color_attribute->getSource()->getAllOptions();
    $sizes = $size_attribute->getSource()->getAllOptions();
    $fits = $fit_attribute->getSource()->getAllOptions();

    $color_options = [];
    foreach ($colors as $color) {
        $color_options[$color['label']] = $color['value'];
    }


    $size_options = [];
    foreach ($sizes as $size) {
        $size_options[$size['label']] = $size['value'];
    }


    $fit_options = [];
    foreach ($fits as $fit) {
        $fit_options[$fit['label']] = $fit['value'];
    }

    $tmpDir = $directoryList->getPath(Magento\Framework\App\Filesystem\DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
    $fileSystem->checkAndCreateFolder($tmpDir);


    $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
    $stores = $storeManager->getStores();
    $storeArray[0] = "All Store Views";
    foreach ($stores as $store) {
        $storeArray[$store->getId()] = $store->getName();
    }

    try {
        $query = "SELECT * FROM variations ORDER BY `Style`";
        $rows = $customConnection->fetchAll($query);
    } catch (\Exception $e) {
        echo "Error fetching data from custom database: " . $e->getMessage() . "\n";
    }

    $groupedData = [];

    foreach ($rows as $row) {
        $groupedData[$row['Style']][] = $row;
    }

    $rootCategoryId = $storeManager->getStore()->getRootCategoryId();

    // Process each group of data
    foreach ($groupedData as $styleCode => $items) {

        $configurableProductName = $styleCode . '-' . $items[0]['Desc'];

        try {
            $productDescQuery = "SELECT * FROM product_desc WHERE `Style` = ?";
            $productDesc = $customConnection->fetchRow($productDescQuery, [$styleCode]);
            // Debug the products result
        } catch (\Exception $e) {
            echo "Error fetching product Desc for Style Code " . $styleCode . ": " . $e->getMessage() . "\n";
            continue;
        }

        if (!$productDesc) {
            echo "No Description For product have Style Code: " . $styleCode . "\n";
            continue;
        }

        try {
            $productCategoryQuery = "SELECT * FROM product_prices WHERE `Style` = ?";
            $productCategoryData = $customConnection->fetchRow($productCategoryQuery, [$styleCode]);
            // Debug the products result
        } catch (\Exception $e) {
            echo "Error fetching product Desc for Style Code " . $styleCode . ": " . $e->getMessage() . "\n";
            continue;
        }

        if (!$productCategoryData || is_null($productCategoryData['ProductRange'] || is_null($productCategoryData['ProductGroup']))) {
            echo "No Category Or SubCategory For product have Style Code: " . $styleCode . "\n";
            continue;
        }


        $formattedFeatures = '<ul>';

        for ($i = 1; $i <= 32; $i++) {
            $featureKey = 'Features' . $i;
            if (isset($productDesc[$featureKey])) {
                $feature = $productDesc[$featureKey];
                if (!is_null($feature)) {
                    $trimmedFeature = trim($feature);
                    if (!empty($trimmedFeature)) {
                        $formattedFeatures .= '<li>' . htmlspecialchars($trimmedFeature) . '</li>';
                    }
                }
            }
        }

        $formattedFeatures .= '</ul>';

        if (isset($productDesc['Description']) && !empty($productDesc['Description']) && preg_match('/<ul>(\s*<li>.*<\/li>\s*)+<\/ul>/', $formattedFeatures)) {
            // Both description and features are available
            $formattedDescription = htmlspecialchars($productDesc['Description']) . '<br><br><strong>Features:</strong><br>' . $formattedFeatures;
        } elseif (isset($productDesc['Description']) && !empty($productDesc['Description'])) {
            // Only description is available
            $formattedDescription = htmlspecialchars($productDesc['Description']);
        } elseif (preg_match('/<ul>(\s*<li>.*<\/li>\s*)+<\/ul>/', $formattedFeatures)) {
            // Only features are available
            $formattedDescription = '<br><br><strong>Features:</strong><br>' . $formattedFeatures;
        } else {
            // Neither description nor features are available
            $formattedDescription = 'No Data';
        }

        $productRange = $productCategoryData['ProductRange'];
        $productGroup = $productCategoryData['ProductGroup'];

        // Get or create ProductRange category

        $productRangeCategory = getCategory($productRange, $rootCategoryId, $objectManager);
        echo "Category: {$productRangeCategory->getId()}\n";

        // Get or create ProductGroup category under ProductRange
        $productGroupCategory = getCategory($productGroup, $productRangeCategory->getId(), $objectManager);
        echo "Sub Category: {$productGroupCategory->getId()}\n";

        $simpleProductIds = []; // Array to hold IDs of associated simple products
        $simpleProductImages = []; // Array to hold IDs of associated simple products

        echo "Start with Items loop\n";
        // Create Simple Products and associate with Configurable Product
        foreach ($items as $item) {

            try {
                $itemPriceQuery = "SELECT * FROM product_prices WHERE `ItemCode` = ?";
                $itemPriceData = $customConnection->fetchRow($itemPriceQuery, [$item['Item']]);
                // Debug the products result
            } catch (\Exception $e) {
                echo "Error fetching product price for Item Code " . $item['Item'] . ": " . $e->getMessage() . "\n";
                continue;
            }

            $productName = $item['Desc'];
            echo "Processing Simple Product: " . $productName . " --- " . $item['Item'] . "\n";

            try {
                $simpleProduct = $productRepository->get($item['Item']);
            } catch (Exception $ex) {
                echo("Simple Product Not Found, creating it \n ");
                $simpleProduct = false;
            }

            if (!$simpleProduct) {
                // Create Simple Product
                $simpleProduct = $objectManager->create('Magento\Catalog\Model\Product');
                $simpleProduct->setSku($item['Item'])
                    ->setName($item['Item'] . '-' . $item['Desc'])
                    ->setAttributeSetId(9) // Set your attribute set ID for simple products
                    ->setStatus(1) // Enabled
                    ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE)
                    ->setTypeId('simple')
                    ->setPrice($itemPriceData['Price'])
                    ->setWeight($item['Weight(Kg)'])
                    ->setWebsiteIds([1])// Default website
                    ->setCategoryIds([$productRangeCategory->getId(), $productGroupCategory->getId()]) // Adjust category IDs as per your structure
                    ->setStockData([
                        'qty' => 10,
                        'is_in_stock' => 1
                    ]);

                if ($item['Colour']) {
                    $simpleProduct->setData('color', $color_options[$item['Colour']]);

                }


                if ($item['Size']) {
                    $simpleProduct->setData('size', $size_options[$item['Size']]);
                }

                if ($item['Fit'] && $item['Fit'] !== "") {
                    $simpleProduct->setData('fit', $fit_options[$item['Fit']]);
                }


                if ($item['Image_Path']) {
                    $newFileName = $tmpDir . baseName($item['Image_Path']);
                    $result = $fileSystem->read($item['Image_Path'], $newFileName);
                    if ($result) {
                        $simpleProduct->addImageToMediaGallery($newFileName, array('image', 'small_image', 'thumbnail'), true, false);
                        $simpleProductImages[] = $item['Image_Path'];
                    }
                }


                try {
                    $productRepository->save($simpleProduct);
                    $simpleProduct = $productRepository->get($item['Item']);

                } catch (Exception $e) {
                    echo "Error Saving Simple Product" . $e->getMessage();
                    continue;
                }
            } else {
                echo "Simple Product found with ID:" . $simpleProduct->getId() . "\n";
            }
            $simpleProductIds[] = $simpleProduct->getId(); // Collect simple product IDs


        }

        print_r($simpleProductIds);
        echo "Processing Configurable Product: " . $productName . " --- '" . $styleCode . "'\n";


        try {
            $configurableproduct = $productRepository->get($styleCode);
        } catch (Exception $ex) {
            print_r("Configurable Product Not Found, creating it \n ");
            $configurableproduct = false;
        }


        if (!$configurableproduct) {

            $configurableproduct = $objectManager->create('Magento\Catalog\Model\Product');
            $configurableproduct->setSku($styleCode); // set Your SKU
            $configurableproduct->setName($configurableProductName); // set Your Configurable Name
            $configurableproduct->setAttributeSetId(9); // set attribute id
            $configurableproduct->setStatus(1); // status enabled/disabled 1/0
            $configurableproduct->setTypeId('configurable'); // type of product (simple/virtual/downloadable/configurable)
            $configurableproduct->setVisibility(4);  // visibility of product (Not Visible Individually (1) / Catalog (2)/ Search (3)/ Catalog, Search(4))
            $configurableproduct->setPrice(0);
            $configurableproduct->setShortDescription($formattedDescription);
            $configurableproduct->setTaxClassId(0); // Tax class ID
            $configurableproduct->setWebsiteIds(array(1)); // set website Id
            $configurableproduct->setCategoryIds([$productRangeCategory->getId(), $productGroupCategory->getId()]); // Adjust category IDs as per your structure
            $configurableproduct->setStockData(array(
                    'use_config_manage_stock' => 0,
                    'manage_stock' => 1,
                    'is_in_stock' => 1,
                )
            );


            $configurableproduct->setData('product_page_type', 'default'); // set website Id


            $configurableattributesdata = $configurableproduct->getTypeInstance()->getConfigurableAttributesAsArray($configurableproduct);
            $configurableproduct->setCanSaveConfigurableAttributes(true);
            $configurableproduct->setConfigurableAttributesData($configurableattributesdata);
            $configurableproductsdata = array();
            $configurableproduct->setConfigurableProductsData($configurableproductsdata);


            $size_attr_id = $configurableproduct->getResource()->getAttribute('size')->getId();
            $color_attr_id = $configurableproduct->getResource()->getAttribute('color')->getId();
            $fit_attr_id = $configurableproduct->getResource()->getAttribute('fit')->getId();

            $configurableproduct->getTypeInstance()->setUsedProductAttributeIds(array($color_attr_id, $size_attr_id, $fit_attr_id), $configurableproduct); //attribute ID of attribute 'size_general' in my store

            $configurableAttributesData = $configurableproduct->getTypeInstance()->getConfigurableAttributesAsArray($configurableproduct);
            $configurableproduct->setCanSaveConfigurableAttributes(true);
            $configurableproduct->setConfigurableAttributesData($configurableAttributesData);
            $configurableProductsData = array();
            $configurableproduct->setConfigurableProductsData($configurableProductsData);

            $simpleProductImages = array_unique($simpleProductImages);
            foreach ($simpleProductImages as $simpleProductImage) {
                $newFileName = $tmpDir . baseName($simpleProductImage);
                $result = $fileSystem->read($simpleProductImage, $newFileName);
                if ($result) {
                    $configurableproduct->addImageToMediaGallery($newFileName, array('image', 'small_image', 'thumbnail'), true, false);
                }
            }

            try {
                $configurableproduct->save();
            } catch (Exception $ex) {
                echo "Error Saving Bundle Product: " . $ex->getMessage();
                continue;
            }
            $product_id = $configurableproduct->getId();
            $associatedproductids = $simpleProductIds;

            try {
                $configurableproduct_load = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
                $configurableproduct_load->setAssociatedProductIds($associatedproductids);
                $configurableproduct_load->setCanSaveConfigurableAttributes(true);
                $configurableproduct_load->save();
                echo "configurable product save successfully \n";
            } catch (Exception $e) {
                echo "Error Attaching Simple to Bundle Product: " . $e->getMessage();
                continue;
            }
        } else {
            echo "Configurable Product found with ID:" . $simpleProduct->getId() . "\n";

        }

    }
} catch (CouldNotSaveException $e) {
    echo $e->getMessage();
}


function getCategory($categoryName, $parentId, $objectManager)
{
    echo "getCategory: " . $categoryName . "\n";

    $categoryFactory = $objectManager->get(CategoryFactory::class);
    $categoryRepository = $objectManager->get(CategoryRepository::class);
    $category = $categoryFactory->create();
    $categoryCollection = $category->getCollection()->addAttributeToFilter('name', $categoryName)->addAttributeToFilter('parent_id', $parentId)->setPageSize(1);

    if ($categoryCollection->getSize()) {
        echo "Exists\n";
        return $categoryCollection->getFirstItem();
    } else {
        echo "Create New\n";
        $category->setName($categoryName);
        $category->setIsActive(true);
        $category->setParentId($parentId);
        $category->setStoreId(0);
        $categoryRepository->save($category);

        $category->setPath($categoryRepository->get($parentId)->getPath() . '/' . $category->getId());
        $categoryRepository->save($category);

        return $category;
    }
}


?>

Spamworldpro Mini