This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,212 @@
<?php
namespace Stemcell\ProductImport\Cron;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableProductType;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Storage\WriterInterface as ConfigWriter;
use Magento\Framework\App\State;
use Magento\Framework\Exception\AlreadyExistsException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Filesystem;
use Magento\Framework\Module\Dir;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Indexer\Model\Indexer\CollectionFactory as IndexerCollectionFactory;
use Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory;
use Magento\InventoryApi\Api\SourceItemsSaveInterface;
use PHP_CodeSniffer\Tokenizers\PHP;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Psr\Log\LoggerInterface;
use Stemcell\ProductImport\Model\Import\Status;
use Stemcell\ProductImport\Model\Import\TypeId;
use Stemcell\ProductImport\Model\ImportTask;
use Stemcell\ProductImport\Model\ResourceModel\ImportTask as ImportTaskResource;
use Stemcell\ProductImport\Model\ResourceModel\ImportTask\CollectionFactory as ImportTaskCollection;
class ImportPrice
{
const NO_PRICE_SKU_PATH = 'catalog/product_settings/no_price_sku';
private bool $needReindex = false;
public function __construct(
protected State $state,
protected ProductRepositoryInterface $productRepository,
protected LoggerInterface $logger,
protected ProductCollection $productCollection,
protected Dir $dir,
protected SourceItemsSaveInterface $sourceItemsSave,
protected SourceItemInterfaceFactory $sourceItemFactory,
protected ConfigurableProductType $configurableProductType,
protected StockRegistryInterface $stockRegistry,
protected ImportTaskCollection $importTaskCollection,
protected IndexerCollectionFactory $indexerCollectionFactory,
protected ImportTaskResource $importTaskResource,
protected ConfigWriter $configWriter,
protected TimezoneInterface $timezone,
protected TypeListInterface $cacheTypeList,
) {
}
protected function getSpreadsheet()
{
$path = $this->dir->getDir('Stemcell_ProductImport').'/data/product-stock.xlsx';
if (!file_exists($path)) {
throw new \Exception(sprintf('File %s does not exist', $path));
}
return IOFactory::load($path);
}
public function getParentSku(int $childId): string
{
$parentIds = $this->configurableProductType->getParentIdsByChild($childId);
try {
if (!empty($parentIds)) {
$parent = $this->productRepository->getById(current($parentIds));
return $parent->getSku();
}
} catch (NoSuchEntityException $e) {
}
return '';
}
/**
* @param ImportTask $importTask
* @return void
* @throws NoSuchEntityException
* @throws \Exception
*/
protected function runItem(ImportTask $importTask)
{
$filePath = $importTask->getFilePath();
if (!$filePath || !file_exists($filePath)) {
throw new \Exception(sprintf('导入库存的任务: %d中,要导入的文件:%s不存在' . $importTask->getId(), $importTask->getFilePath()));
}
$spreadsheet = IOFactory::load($importTask->getFilePath());
$sheet = $spreadsheet->getActiveSheet();
$price = [];
echo $importTask->getFilePath().PHP_EOL;
foreach($sheet->toArray() as $item) {
$pr = $item[1];
if ($pr) {
$pr = (float) str_replace(',', '', $item[1]);
}
$price[$item[0]] = $pr;
}
$products = $this->productCollection->addAttributeToFilter('type_id', 'simple');
$noPriceSkus = [];
$importTask->setData('status', Status::PROCESSING->value);
$importTask->setData('updated_at', null);
$this->importTaskResource->save($importTask);
/* @var $product Product */
foreach ($products as $product) {
if (!isset($price[$product->getSku()])) {
$noPriceSkus[] = $product->getSku();
}
try {
// 以 admin store 加载,避免 store scope 问题
$product = $this->productRepository->get($product->getSku(), false, 0, true);
$pr = isset($price[$product->getSku()]) ? $price[$product->getSku()] : 0;
echo 'sku: '.$product->getSku().', price: '.$pr.PHP_EOL;
$product->setPrice($pr);
$this->productRepository->save($product);
} catch (\Exception $e) {
}
}
$parentSkus = [];
foreach ($noPriceSkus as $sku) {
$simple = $this->productRepository->get($sku);
$parentIds = $this->configurableProductType->getParentIdsByChild($simple->getId());
if (empty($parentIds)) {
continue;
}
foreach ($parentIds as $parentId) {
$parent = $this->productRepository->getById($parentId);
$parentSkus[$sku] = $parent->getSku();
}
}
$parentSkus = array_unique(array_values($parentSkus));
// echo implode(',', $parentSkus).PHP_EOL;
try {
if (!empty($parentSkus)) {
// $this->configWriter->delete(self::NO_PRICE_SKU_PATH);
$this->configWriter->save(
self::NO_PRICE_SKU_PATH,
implode(',', $parentSkus),
ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
0
);
$this->cacheTypeList->cleanType('config');
}
} catch (\Exception $e) {
$this->logger->critical(sprintf('设置产品价格到config时异常:%s', $e->getMessage()));
}
}
public function execute()
{
$collection = $this->importTaskCollection->create()
->setItemObjectClass(ImportTask::class)
->addFieldToFilter('type_id', TypeId::PRICE->value)
->addFieldToFilter('status', Status::PENDING->value);
/* @var $item ImportTask */
foreach ($collection as $item) {
echo $item->getId().PHP_EOL;
try {
$this->needReindex = false;
$this->runItem($item);
$item->setData('status', Status::SUCCESS->value);
$item->setData('message', '导入产品价格成功');
} catch (\Exception $e) {
$this->logger->critical(sprintf('导入产品价格时异常:%s', $e->getMessage()));
$item->setData('status', Status::FAILED->value);
$item->setData('message', $e->getMessage());
}
$item->setData('updated_at', $this->timezone->date()->format('Y-m-d H:i:s'));
try {
$this->importTaskResource->save($item);
} catch (AlreadyExistsException $e) {
$this->logger->critical(sprintf('更新产品价格:%d时异常:%s', $item->getId(), $e->getMessage()));
}
}
$indexers = ['catalog_product_price'];
if ($this->needReindex) {
$collection = $this->indexerCollectionFactory->create()
// ->addFieldToFilter('indexer_id', ['in' => ['cataloginventory_stock', 'inventory']])
->getItems();
foreach ($collection as $indexer) {
try {
if (in_array($indexer->getId(), $indexers)) {
$indexer->reindexAll();
// echo $indexer->getTitle().PHP_EOL;
}
} catch (\Exception $e) {
$this->logger->critical(sprintf('导入产品价格完成后,刷新索引indexer时异常:%s', $e->getMessage()));
}
}
}
}
}
@@ -0,0 +1,184 @@
<?php
namespace Stemcell\ProductImport\Cron;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableProductType;
use Magento\Framework\App\State;
use Magento\Framework\Exception\AlreadyExistsException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Filesystem;
use Magento\Framework\Module\Dir;
use Magento\Indexer\Model\Indexer\CollectionFactory as IndexerCollectionFactory;
use Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory;
use Magento\InventoryApi\Api\SourceItemsSaveInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Psr\Log\LoggerInterface;
use Stemcell\ProductImport\Model\Import\Status;
use Stemcell\ProductImport\Model\Import\TypeId;
use Stemcell\ProductImport\Model\ImportTask;
use Stemcell\ProductImport\Model\ResourceModel\ImportTask as ImportTaskResource;
use Stemcell\ProductImport\Model\ResourceModel\ImportTask\CollectionFactory as ImportTaskCollection;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
/**
* (1)magento的简单产品(simple)可能包含一个或多个小货号 @var \Stemcell\SubItemProduct\Console\Command\SubItemImport 命令会
* 导入大小货号配比,也会初始化小货号库存
* (2) 导入小货号的库存,不在本次导入中的小货号库存会被清零
*/
class ImportStock
{
private bool $needReindex = false;
public function __construct(
protected State $state,
protected ProductRepositoryInterface $productRepository,
protected LoggerInterface $logger,
protected ProductCollection $productCollection,
protected Dir $dir,
protected SourceItemsSaveInterface $sourceItemsSave,
protected SourceItemInterfaceFactory $sourceItemFactory,
protected ConfigurableProductType $configurableProductType,
protected StockRegistryInterface $stockRegistry,
protected ImportTaskCollection $importTaskCollection,
protected IndexerCollectionFactory $indexerCollectionFactory,
protected ImportTaskResource $importTaskResource,
protected TimezoneInterface $timezone
) {
}
protected function getSpreadsheet()
{
$path = $this->dir->getDir('Stemcell_ProductImport').'/data/product-stock.xlsx';
if (!file_exists($path)) {
throw new \Exception(sprintf('File %s does not exist', $path));
}
return IOFactory::load($path);
}
public function getParentSku(int $childId): string
{
$parentIds = $this->configurableProductType->getParentIdsByChild($childId);
try {
if (!empty($parentIds)) {
$parent = $this->productRepository->getById(current($parentIds));
return $parent->getSku();
}
} catch (NoSuchEntityException $e) {
}
return '';
}
/**
* @throws NoSuchEntityException
*/
protected function updateStock(string $sku, int $qty): void
{
$stockItem = $this->stockRegistry->getStockItemBySku($sku);
$stockItem->setManageStock(true);
$stockItem->setIsInStock(true);
$stockItem->setQty($qty);
$stockItem->setUseConfigManageStock(true);
$stockItem->setBackorders(1);
$stockItem->setUseConfigBackorders(false);
$this->stockRegistry->updateStockItemBySku(
$sku,
$stockItem
);
}
/**
* @param ImportTask $importTask
* @return void
* @throws NoSuchEntityException
* @throws \Exception
*/
protected function runItem(ImportTask $importTask)
{
$filePath = $importTask->getFilePath();
if (!$filePath || !file_exists($filePath)) {
throw new \Exception(sprintf('导入库存的任务: %d中,要导入的文件:%s不存在' . $importTask->getId(), $importTask->getFilePath()));
}
$spreadsheet = IOFactory::load($importTask->getFilePath());
$sheet = $spreadsheet->getActiveSheet();
$stock = [];
foreach($sheet->toArray() as $index => $item) {
if ($index==0) {
continue;
}
$stock[$item[0]] = $item[1];
}
foreach ($stock as $sku => $qty) {
try {
$this->importTaskResource->getConnection()->query("
update subitem_product set stock_qty = $qty where sub_sku='$sku'
");
} catch (\Exception $e) {
$this->logger->critical(sprintf('更新subitem_product sub_sku: %s数据失败,原因:%s', $sku,$e->getMessage()));
}
}
if (!empty($stock)) {
$this->importTaskResource->getConnection()->query("
update subitem_product set stock_qty = 0 where sub_sku not in (" . "'". implode("','", array_keys($stock)) . "')"
);
}
}
public function execute()
{
$collection = $this->importTaskCollection->create()
->setItemObjectClass(ImportTask::class)
->addFieldToFilter('type_id', TypeId::STOCK->value)
->addFieldToFilter('status', Status::PENDING->value);
/* @var $item ImportTask */
foreach ($collection as $item) {
try {
$this->needReindex = false;
$this->runItem($item);
$item->setData('status', Status::SUCCESS->value);
$item->setData('message', '导入产品库存成功');
} catch (\Exception $e) {
$this->logger->critical(sprintf('导入产品库存时异常:%s', $e->getMessage()));
$item->setData('status', Status::FAILED->value);
$item->setData('message', $e->getMessage());
}
$item->setData('updated_at', $this->timezone->date()->format('Y-m-d H:i:s'));
try {
$this->importTaskResource->save($item);
} catch (AlreadyExistsException $e) {
$this->logger->critical(sprintf('更新产品库存:%d时异常:%s', $item->getId(), $e->getMessage()));
}
}
// $indexers = ['cataloginventory_stock', 'inventory'];
// if ($this->needReindex) {
// $collection = $this->indexerCollectionFactory->create()
//// ->addFieldToFilter('indexer_id', ['in' => ['cataloginventory_stock', 'inventory']])
// ->getItems();
//
// foreach ($collection as $indexer) {
//
// try {
// if (in_array($indexer->getId(), $indexers)) {
// $indexer->reindexAll();
//// echo $indexer->getTitle().PHP_EOL;
// }
//
// } catch (\Exception $e) {
// $this->logger->critical(sprintf('导入产品库存完成后,刷新索引indexer时异常:%s', $e->getMessage()));
// }
// }
// }
}
}