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,295 @@
<?php
namespace Stemcell\Catalog\Console\Command;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Visibility;
use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable;
use Magento\Framework\Module\Dir;
use Stemcell\Catalog\Model\ResourceModel\CellType as CellTypeResource;
use Stemcell\Catalog\Model\ResourceModel\CellSubType as CellSubTypeResource;
use Stemcell\Catalog\Model\ResourceModel\Species as SpeciesResource;
use Stemcell\Catalog\Model\ResourceModel\Tissue as TissueResource;
use Stemcell\Catalog\Model\ResourceModel\CellSort as CellSortResource;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Serialize\Serializer\Json;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Magento\Eav\Model\ResourceModel\ReadHandler;
/**
* 细胞分选工具数据导入
* 调用此接口前,请先运行一次cell:sort:import命令,导入数据
*/
class CellSortImport extends Command
{
protected $parentProduct = [];
protected OutputInterface $output;
public function __construct(
private Dir $dir,
private File $file,
private Json $json,
private SpeciesResource $speciesResource,
private CellTypeResource $cellTypeResource,
private CellSubTypeResource $cellSubTypeResource,
private TissueResource $tissueResource,
private CellSortResource $cellSortResource,
private Configurable $configurableProduct,
private ProductRepositoryInterface $productRepository,
){
parent::__construct('cell:sort:import');
$this->setDescription('细胞分选工具数据导入');
}
/**
* @return void
* @throws \Magento\Framework\Exception\FileSystemException
*/
protected function getPcas() {
$pcas = $this->dir->getDir('Stemcell_Catalog').'/data/pcas-code.json';
foreach ($this->json->unserialize($this->file->fileGetContents($pcas)) as $item) {
$this->provinces[$item['name']] = str_pad($item['code'], 6, '0');
}
}
protected function getSpreadsheet()
{
$path = $this->dir->getDir('Stemcell_Catalog').'/data/cell-select-tool.xlsx';
if (!file_exists($path)) {
throw new \Exception(sprintf('File %s does not exist', $path));
}
return IOFactory::load($path);
}
protected function getParentProduct(string $childSku)
{
try {
if (!isset($this->parentProduct[$childSku])) {
$product = $this->productRepository->get($childSku);
if ($product->getVisibility()== Visibility::VISIBILITY_NOT_VISIBLE) {
$parentIds = $this->configurableProduct->getParentIdsByChild($product->getId());
if (!empty($parentIds)) {
$configurableProduct = $this->productRepository->getById(reset($parentIds));
$this->parentProduct[$childSku] = $configurableProduct->getSku();
}
}
}
return $this->parentProduct[$childSku];
} catch (\Exception $exception) {
$this->output->writeln('<error>' . sprintf('get parent product from %s fail', $childSku) . '</error>, because: ' . $exception->getMessage());
}
return null;
}
/**
* 删除旧数据
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function previousDataClean()
{
$this->speciesResource->getConnection()->query('TRUNCATE TABLE '.$this->speciesResource->getMainTable());
$this->cellTypeResource->getConnection()->query('TRUNCATE TABLE '.$this->cellTypeResource->getMainTable());
$this->cellSubTypeResource->getConnection()->query('TRUNCATE TABLE '.$this->cellSubTypeResource->getMainTable());
$this->tissueResource->getConnection()->query('TRUNCATE TABLE '.$this->tissueResource->getMainTable());
$this->cellSortResource->getConnection()->query('TRUNCATE TABLE '.$this->cellSortResource->getMainTable());
}
/**
* @param array $data
* @return array
*/
protected function getSpecies(array $data)
{
$species = [];
foreach ($data as $item) {
$species[$item['species']] = ['species_name' => $item['species'], 'species_sort' => $item['specieSort']];
}
return array_values($species);
}
/**
* @param array $data
* @return array
*/
protected function getCellType(array $data)
{
$cellTypes = [];
foreach ($data as $item) {
$cellTypes[$item['cellType']] = ['cell_type_name' => $item['cellType'], 'cell_type_sort' => $item['cellTypeSort']];
}
return array_values($cellTypes);
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->previousDataClean();
$spreadsheet = $this->getSpreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$lastRow = $sheet->getHighestRow();
$temp = $data = [];
for ($row = 2; $row <= $lastRow; ++$row) {
$skus = $sheet->getCell('J' . $row)->getValue();
if ($skus) {
$species = $sheet->getCell('B' . $row)->getValue();
$specieSort = intval(trim((string)$sheet->getCell('C' . $row)->getValue()));
$cellType = $sheet->getCell('D' . $row)->getValue();
$cellTypeSort = intval(trim((string)$sheet->getCell('E' . $row)->getValue()));
$cellSubType = $sheet->getCell('F' . $row)->getValue();
$cellSubTypeSort = $sheet->getCell('K' . $row)->getValue();
$tissue = explode("\n", (string)$sheet->getCell('G' . $row)->getValue());
$positive = $sheet->getCell('H' . $row)->getValue();
$negative = $sheet->getCell('I' . $row)->getValue();
$skus = explode("\n", $skus);
$temp[$row] = [
'species'=>trim($species), 'specieSort'=>$specieSort, 'cellType'=>trim($cellType), 'cellTypeSort'=>$cellTypeSort,
'cellSubType'=>trim($cellSubType), 'cellSubTypeSort'=>$cellSubTypeSort, 'tissue'=>$tissue, 'positive'=>$positive, 'negative'=>$negative, 'sku'=>$skus
];
}
}
$cellSubTypeData = [];
$maxCellSubTypeSort = 0;
foreach ($temp as $item) {
if (!isset($cellSubTypeData[$item['cellSubType']])) {
$cellSubTypeData[$item['cellSubType']] = ['cellSubType'=>$item['cellSubType'], 'cellSubTypeSort'=>$item['cellSubTypeSort']];
}
if ($item['cellSubTypeSort']) {
$maxCellSubTypeSort = max($maxCellSubTypeSort, $item['cellSubTypeSort']);
}
//处理一个单元格中有多个组织的情况
foreach ($item['tissue'] as $tissue) {
//处理一个单元格中有多个sku的情况
foreach ($item['sku'] as $sku) {
$data[] = [
'species'=>$item['species'], 'specieSort'=>$item['specieSort'], 'cellType'=>$item['cellType'],
'cellTypeSort'=>$item['cellTypeSort'],'cellSubType'=>$item['cellSubType'], 'cellSubTypeSort'=>$item['cellSubTypeSort'], 'tissue'=>trim($tissue),
'positive'=>$item['positive'], 'negative'=>$item['negative'], 'sku'=>trim($sku)
];
}
}
}
$maxCellSubTypeSort++;
foreach ($data as $item) {
$output->writeln(sprintf('<info>%s</info>', implode(', ', $item)));
}
$species = $this->speciesResource->getConnection()->fetchAll('select * from '.$this->speciesResource->getMainTable());
if (empty($species)) {
foreach ($this->getSpecies($data) as $species) {
$this->speciesResource->getConnection()->insert($this->speciesResource->getMainTable(), $species);
}
$species = $this->speciesResource->getConnection()->fetchAll('select * from '.$this->speciesResource->getMainTable());
}
$speciesIndex = [];
foreach ($species as $item) {
$speciesIndex[$item['species_name']] = ['species_id'=>$item['species_id'], 'species_sort'=>$item['species_sort']];
}
unset($species);
$cellTypes = $this->cellTypeResource->getConnection()->fetchAll('select * from '.$this->cellTypeResource->getMainTable());
if (empty($cellTypes)) {
foreach ($this->getCellType($data) as $cellType) {
$this->cellTypeResource->getConnection()->insert($this->cellTypeResource->getMainTable(), $cellType);
}
$cellTypes = $this->cellTypeResource->getConnection()->fetchAll('select * from '.$this->cellTypeResource->getMainTable());
}
$cellTypesIndex = [];
foreach ($cellTypes as $item) {
$cellTypesIndex[$item['cell_type_name']] = ['cell_type_id'=>$item['cell_type_id'], 'cell_type_sort'=>$item['cell_type_sort']];
}
$cellSubTypes = $this->cellTypeResource->getConnection()->fetchAll('select * from '.$this->cellSubTypeResource->getMainTable());
if (empty($cellSubTypes)) {
foreach ($cellSubTypeData as $cellType) {
if (empty($cellType['cellSubTypeSort'])) {
$cellType['cellSubTypeSort'] = $maxCellSubTypeSort;
}
$this->cellTypeResource->getConnection()->insert(
$this->cellSubTypeResource->getMainTable(),
[
'cell_subtype_name' => $cellType['cellSubType'],
'cell_subtype_sort' => $cellType['cellSubTypeSort'],
]
);
}
$cellTypes = $this->cellTypeResource->getConnection()->fetchAll('select * from '.$this->cellSubTypeResource->getMainTable());
}
$cellSubTypesIndex = [];
foreach ($cellTypes as $item) {
$cellSubTypesIndex[$item['cell_subtype_name']] = $item['cell_subtype_id'];
}
unset($cellSubTypes);
$tissues = $this->tissueResource->getConnection()->fetchAll('select * from '.$this->tissueResource->getMainTable());
if (empty($tissues)) {
foreach (array_unique(array_column($data, 'tissue')) as $tissue) {
$this->tissueResource->getConnection()->insert($this->tissueResource->getMainTable(), ['tissue_name' => $tissue]);
}
$tissues = $this->tissueResource->getConnection()->fetchAll('select * from '.$this->tissueResource->getMainTable());
}
$tissueIndex = [];
foreach ($tissues as $item) {
$tissueIndex[$item['tissue_name']] = $item['tissue_id'];
}
unset($tissues);
$cellSorts = $this->cellSortResource->getConnection()->fetchOne('select * from '.$this->cellSortResource->getMainTable());
if (empty($cellSorts)) {
foreach ($data as $item) {
$flag = null;
if ($item['positive']==1) {
$flag = 1;
} elseif ($item['negative']==1) {
$flag = -1;
}
$insertData = [
'species_id' => $speciesIndex[$item['species']]['species_id'],
'species_name' => $item['species'],
'species_sort' => $speciesIndex[$item['species']]['species_sort'],
'cell_type_id' => $cellTypesIndex[$item['cellType']]['cell_type_id'],
'cell_type_sort' => $cellTypesIndex[$item['cellType']]['cell_type_sort'],
'cell_type_name' => $item['cellType'],
'cell_subtype_id' => $cellSubTypesIndex[$item['cellSubType']],
'cell_subtype_name' => $item['cellSubType'],
'cell_subtype_sort' => $item['cellSubTypeSort']?? $maxCellSubTypeSort,
'tissue_id' => $tissueIndex[$item['tissue']],
'tissue_name' => $item['tissue'],
'sku' => $this->getParentProduct($item['sku']),
'flag' => $flag,
];
try {
$this->cellSortResource->getConnection()->insert($this->cellSortResource->getMainTable(), $insertData);
} catch (\Exception $exception) {
$output->writeln(
'<error>insert data into cell_sort_product exception, </error> '.
'exception: '.$exception->getMessage() .', data: '.json_encode($insertData)
);
}
}
}
return 0;
}
}
@@ -0,0 +1,74 @@
<?php
namespace Stemcell\Catalog\Console\Command;
use Magento\Framework\Module\Dir;
use Stemcell\Catalog\Model\ExperimentalSchemeFactory;
use Stemcell\Catalog\Model\ResourceModel\ExperimentalScheme;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
* 从excel中导入实验方案数据
*/
class ExperimentalSchemeImport extends Command
{
protected $parentProduct = [];
public function __construct(
private Dir $dir,
private ExperimentalSchemeFactory $experimentalSchemeFactory,
private ExperimentalScheme $experimentalSchemeResource,
){
parent::__construct('experimental:scheme:import');
$this->setDescription('实验方案数据导入');
}
protected function getSpreadsheet()
{
$path = $this->dir->getDir('Stemcell_Catalog').'/data/experimental-scheme.xlsx';
if (!file_exists($path)) {
throw new \Exception(sprintf('File %s does not exist', $path));
}
return IOFactory::load($path);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
//清除就数据
$this->experimentalSchemeResource->getConnection()->query('TRUNCATE TABLE '.$this->experimentalSchemeResource->getMainTable());
$spreadsheet = $this->getSpreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$lastRow = $sheet->getHighestRow();
for ($row = 2; $row <= $lastRow; ++$row) {
$collectionName = $sheet->getCell('A' . $row)->getValue();
if ($collectionName) {
$collectionName = trim($collectionName);
} else {
break;
}
$collectionSort = intval(trim((string)$sheet->getCell('B' . $row)->getValue()));
$title = trim((string)$sheet->getCell('C' . $row)->getValue());
$imagePath = $sheet->getCell('D' . $row)->getValue();
if ($imagePath) {
$imagePath = 'experimental-scheme/images/'.trim($imagePath);
}
$mpUrl = trim((string)$sheet->getCell('E' . $row)->getValue());
$data = [
'collection_name'=>$collectionName, 'collection_sort'=>$collectionSort, 'title'=>$title, 'image'=>$imagePath, 'mp_url'=>$mpUrl
];
$this->experimentalSchemeFactory->create()->setData($data)->save();
}
return 0;
}
}
@@ -0,0 +1,100 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Stemcell\Catalog\Console\Command;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\State;
use Magento\Framework\Module\Dir;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* 从xlsx导入搜索tag, 此命令执行完成后,需要执行indexer:reindex命令
* 具体的说明参见README.md 1.0
*/
class ImportSearchTagsValue extends Command
{
private const NAME_ARGUMENT = "name";
private const NAME_OPTION = "option";
private array $spu = [];
public function __construct(
private Dir $dir,
private ProductRepository $productRepository,
private State $state,
) {
parent::__construct('stemcell:product:import-search-tag-value');
}
/**
* @return \PhpOffice\PhpSpreadsheet\Spreadsheet
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
protected function getExcelReader()
{
$path = $this->dir->getDir('Stemcell_Catalog').'/data/Current Website Product Model Number.xlsx';
if (!file_exists($path)) {
throw new \Exception(sprintf('File %s does not exist', $path));
}
return IOFactory::createReader('Xlsx')->load($path);
}
/**
* @inheritdoc
*/
protected function execute(
InputInterface $input,
OutputInterface $output
): int {
try {
$worksheet = $this->getExcelReader()->getActiveSheet();
$this->state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
foreach ($worksheet->getRowIterator() as $row) {
$rowIndex = $row->getRowIndex();
if ($rowIndex === 1) {
continue;
}
$sku = $worksheet->getCell('A'.$rowIndex)->getValue();
try {
$searchTag = $worksheet->getCell('B'.$rowIndex)->getValue();
if (empty($searchTag)) {
continue;
}
$product = $this->productRepository->get($sku);
if ($product->getData('search_tags') && str_contains($product->getData('search_tags'), $searchTag)) {
$output->writeln(sprintf('<info>search tags %s already set for product: %s</info>', $searchTag, $sku));
}
$output->writeln(sprintf('product %s search tags: %s', $sku, $searchTag));
$product->addAttributeUpdate('search_tags', $searchTag, 1);
} catch (\Exception $e) {
$output->writeln(sprintf('<error>import search tags value fail:%s, product: %s</error>', $e->getMessage(), $sku));
}
}
} catch (\Exception $e) {
$output->writeln(sprintf('<error>import search tags value exception: %s</error>', $e->getMessage()));
}
return Command::SUCCESS;
}
/**
* @inheritdoc
*/
protected function configure(): void
{
$this->setDescription("从xlsx导入搜索tag, 此命令执行完成后,需要执行indexer:reindex命令");
}
}
@@ -0,0 +1,104 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Stemcell\Catalog\Console\Command;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\State;
use Magento\Framework\Module\Dir;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* 从xlsx导入search term, 此命令执行前需要确保\Stemcell\Catalog\Setup\Patch\Schema\AddSearchTermsProductAttribute已经执行
* 此命令执行完成后,需要确认索引(index)刷新了
*
* 具体的说明参见README.md 2.0
*/
class ImportSearchTermsValue extends Command
{
public function __construct(
private Dir $dir,
private ProductRepository $productRepository,
private State $state,
) {
parent::__construct('stemcell:product:import-search-terms');
}
/**
* @return \PhpOffice\PhpSpreadsheet\Spreadsheet
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
protected function getExcelReader()
{
$path = $this->dir->getDir('Stemcell_Catalog').'/data/Search Terms.xlsx';
if (!file_exists($path)) {
throw new \Exception(sprintf('File %s does not exist', $path));
}
return IOFactory::createReader('Xlsx')->load($path);
}
/**
* @inheritdoc
*/
protected function execute(
InputInterface $input,
OutputInterface $output
): int {
try {
$worksheet = $this->getExcelReader()->getActiveSheet();
$this->state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
foreach ($worksheet->getRowIterator() as $row) {
$rowIndex = $row->getRowIndex();
if ($rowIndex === 1) {
continue;
}
$sku = $worksheet->getCell('A'.$rowIndex)->getValue();
try {
$originalSearchTerms = (string)$worksheet->getCell('B'.$rowIndex)->getValue();
$originalSearchTerms = trim($originalSearchTerms);
if (empty($originalSearchTerms)) {
continue;
}
$originalSearchTerms = str_replace('|', '|', $originalSearchTerms);
$searchTerms = '';
foreach (explode('|', $originalSearchTerms) as $term) {
$searchTerms .= preg_replace('/\s+/', '', $term).'|';
}
if (strcasecmp($originalSearchTerms, $searchTerms) != 0) {
$searchTerms = $searchTerms.$originalSearchTerms;
}
$product = $this->productRepository->get($sku);
// if ($product->getData('search_terms') && str_contains($product->getData('search_terms'), $searchTag)) {
// $output->writeln(sprintf('<info>search terms %s already set for product: %s</info>', $searchTag, $sku));
// }
$output->writeln(sprintf('product %s search terms: %s', $sku, $searchTerms));
$product->addAttributeUpdate('search_terms', $searchTerms, 0);
} catch (\Exception $e) {
$output->writeln(sprintf('<error>import search terms value fail:%s, product: %s</error>', $e->getMessage(), $sku));
}
}
} catch (\Exception $e) {
$output->writeln(sprintf('<error>import search terms value exception: %s</error>', $e->getMessage()));
}
return Command::SUCCESS;
}
/**
* @inheritdoc
*/
protected function configure(): void
{
$this->setDescription("从xlsx导入search terms, 此命令执行完成后,需要执行indexer:reindex命令");
}
}
@@ -0,0 +1,94 @@
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Stemcell\Catalog\Console\Command;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\State;
use Magento\Framework\Module\Dir;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ImportSearchWordValue extends Command
{
private const NAME_ARGUMENT = "name";
private const NAME_OPTION = "option";
private array $spu = [];
public function __construct(
private Dir $dir,
private ProductRepository $productRepository,
private State $state,
) {
parent::__construct('stemcell:catalog:import-search-word-value');
}
/**
* @return \PhpOffice\PhpSpreadsheet\Spreadsheet
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
protected function getExcelReader()
{
$path = $this->dir->getDir('Stemcell_Catalog').'/data/search_words.xlsx';
if (!file_exists($path)) {
throw new \Exception(sprintf('File %s does not exist', $path));
}
return IOFactory::createReader('Xlsx')->load($path);
}
/**
* @inheritdoc
*/
protected function execute(
InputInterface $input,
OutputInterface $output
): int {
try {//100-1723_C
$worksheet = $this->getExcelReader()->getActiveSheet();
$this->state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
foreach ($worksheet->getRowIterator() as $row) {
$rowIndex = $row->getRowIndex();
$spu = $worksheet->getCell('A'.$rowIndex)->getValue();
try {
$searchWords = $worksheet->getCell('C'.$rowIndex)->getValue();
if (empty($searchWords) || in_array($spu, $this->spu)) {
continue;
}
$product = $this->productRepository->get($spu);
$output->writeln(sprintf('product %s search word: %s', $spu, $product->getData('search_words')));
$product->addAttributeUpdate('search_words', $searchWords, 1);
$this->spu[] = $spu;
} catch (\Exception $e) {
$output->writeln(sprintf('<error>import search word value fail:%s, product: %s</error>', $e->getMessage(), $spu));
}
}
} catch (\Exception $e) {
$output->writeln(sprintf('<error>import search word value exception: %s</error>', $e->getMessage()));
}
return Command::SUCCESS;
}
/**
* @inheritdoc
*/
protected function configure(): void
{
$this->setDescription("Test script");
$this->setDefinition([
new InputArgument(self::NAME_ARGUMENT, InputArgument::OPTIONAL, "Name"),
new InputOption(self::NAME_OPTION, "-a", InputOption::VALUE_NONE, "Option functionality")
]);
parent::configure();
}
}
@@ -0,0 +1,96 @@
<?php
namespace Stemcell\Catalog\Console\Command;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\State;
use Magento\Framework\Console\Cli;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Module\Dir;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ParentSkuNameImport extends Command
{
public function __construct(
private ProductRepositoryInterface $productRepository,
private readonly Dir $dir,
private readonly State $state,
) {
$name = 'product:parent_sku:name:import';
parent::__construct($name);
}
protected function getSpreadsheet()
{
$path = $this->dir->getDir('Stemcell_Catalog').'/data/PIS.xlsx';
if (!file_exists($path)) {
throw new \Exception(sprintf('File %s does not exist', $path));
}
return IOFactory::load($path);
}
/**
* @throws LocalizedException
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$spreadsheet = $this->getSpreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$lastRow = $sheet->getHighestRow();
$this->state->setAreaCode('adminhtml');
$notExistSku = [];
for ($row = 2; $row <= $lastRow; ++$row) {
$pisSku = trim((string)$sheet->getCell('A' . $row)->getValue());
$parentsProduct = [
[
'sku'=>trim((string)$sheet->getCell('B' . $row)->getValue()),
'name'=>trim((string)$sheet->getCell('C' . $row)->getValue()),
],
[
'sku'=>trim((string)$sheet->getCell('D' . $row)->getValue()),
'name'=>trim((string)$sheet->getCell('E' . $row)->getValue()),
]
];
try {
$pisProduct = $this->productRepository->get($pisSku, true);
$skus = [];
foreach ($parentsProduct as $parentProduct) {
if ($parentProduct['sku']) {
try {
$product = $this->productRepository->get($parentProduct['sku'], true);
$product->setName($parentProduct['name']);
$this->productRepository->save($product);
$skus[] = $parentProduct['sku'];
} catch (NoSuchEntityException $e) {
if (!in_array($parentProduct['sku'], $notExistSku)) {
$notExistSku[] = $parentProduct['sku'];
}
$output->writeln(sprintf('<error>产品: %s 不存在</error>', $parentProduct['sku']));
}
}
}
if (!empty($skus)) {
$parentSku = implode(',', $skus);
if ($pisProduct->getData('parent_skus')) {
$originParentSku = explode(',', $pisProduct->getData('parent_skus'));
$parentSku = implode(',', array_unique(array_merge($originParentSku, $skus)));
}
$pisProduct->setData('parent_skus', $parentSku);
$this->productRepository->save($pisProduct);
}
}catch (\Exception $exception){
$output->writeln(sprintf(' <error>PIS: %s </error>导入时发生异常:%s', $pisSku,$exception->getMessage()));
}
}
$output->writeln(sprintf('<error>产品不存在的SKU: %s</error>', implode(',', $notExistSku)));
return Cli::RETURN_SUCCESS;
}
}
@@ -0,0 +1,95 @@
<?php
namespace Stemcell\Catalog\Console\Command;
use Stemcell\Catalog\Model\ProductManualSearch;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Category;
class ProductManualSearchImport extends Command
{
const PRODUCT_SHEET_CATEGORY_URL_KEY = 'product-information-sheets';
private int $productSheetCategoryId = 0;
public function __construct(
private ProductResource $productResource,
private ProductResource\CollectionFactory $productCollectionFactory,
private Category $category,
private ProductManualSearch $productManualSearch,
) {
parent::__construct('product:manual:search:import');
$this->setDescription('导入产品说明书搜索数据');
}
/**
* @return array
*/
protected function getDataSource()
{
$sql = "
SELECT catalog_product_entity_varchar.`value` as sku, catalog_product_entity.sku as search_sku
FROM catalog_product_entity_varchar
LEFT JOIN catalog_product_entity on catalog_product_entity.entity_id=catalog_product_entity_varchar.entity_id
WHERE catalog_product_entity_varchar.`value` is not NULL and catalog_product_entity_varchar.attribute_id=
(SELECT attribute_id FROM eav_attribute WHERE attribute_code='parent_skus')
";
return $this->productResource->getConnection()->fetchAll($sql);
}
/**
* @return int
*/
protected function getProductSheetCategoryId()
{
if (!$this->productSheetCategoryId){
$category = $this->category->loadByAttribute('url_key', self::PRODUCT_SHEET_CATEGORY_URL_KEY);
$this->productSheetCategoryId = $category? intval($category->getId()) : 0;
}
return $this->productSheetCategoryId;
}
/**
* @param array $skus
* @return ProductResource\Collection
*/
protected function getProductFromSkus(array $skus){
return $this->productCollectionFactory->create()->addAttributeToSelect('name', true)->addCategoryIds()
->addAttributeToFilter('sku', ['in' => $skus]);
}
protected function addNewRecord(array $record)
{
if (isset($record['name']) && isset($record['sku']) && isset($record['search_sku'])) {
$sql = "INSERT INTO product_manual_search (name, sku, search_sku) select \"".$record['name']."\",'".$record['sku']
."','".$record['search_sku'].'\' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM product_manual_search WHERE sku="'.$record['sku'].'" and search_sku="'.$record['search_sku'].'")';
// echo "\r\n";
// echo $sql."\r\n";
$this->productResource->getConnection()->query($sql);
}
}
public function doRun()
{
foreach ($this->getDataSource() as $product) {
foreach ($this->getProductFromSkus(explode(',', $product['sku'])) as $item) {
/* @var $item Product */
$data = ['name' => $item->getName(), 'sku' => $item->getSku(), 'search_sku' => $product['search_sku']];
$this->addNewRecord($data);
}
}
}
public function execute(InputInterface $input, OutputInterface $output)
{
//$this->productResource->getConnection()->query('TRUNCATE TABLE product_manual_search');
$this->doRun();
return Command::SUCCESS;
}
}
@@ -0,0 +1,106 @@
<?php
namespace Stemcell\Catalog\Console\Command;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\CategoryRepository;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\SearchCriteriaBuilder;
use Magento\Framework\App\Filesystem\DirectoryList;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Catalog\Helper\Product as ProductHelper;
class ProductSimpleExport extends Command
{
/**
* @var string[]
*/
private array $category = [];
public function __construct(
private ProductRepositoryInterface $productRepository,
private SearchCriteriaBuilder $searchCriteriaBuilder,
private FilterBuilder $filterBuilder,
private CategoryRepository $categoryRepository,
private ProductHelper $productHelper,
private DirectoryList $directoryList
) {
parent::__construct('stemcell:product:simple_export');
}
/**
* @param int $categoryId
* @return string
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
protected function getCategory(int $categoryId) {
if (!$categoryId) {
return '';
}
if (!isset($this->category[$categoryId])) {
$category = $this->categoryRepository->get($categoryId);
$this->category[$categoryId] = $category->getName()??'';
}
return $this->category[$categoryId];
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$filePath = $this->directoryList->getPath(DirectoryList::VAR_DIR) . '/export/product.xlsx';
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getColumnDimension('A')->setAutoSize(true);
$sheet->getColumnDimension('B')->setAutoSize(true);
$sheet->getColumnDimension('C')->setAutoSize(true);
$sheet->getColumnDimension('D')->setAutoSize(true);
$sheet->getColumnDimension('E')->setAutoSize(true);
$sheet->getStyle('1')->getFont()->setBold(true);
$sheet->setCellValueExplicit('A1', '主货号', DataType::TYPE_STRING)
->setCellValue('B1', 'Product Type')
->setCellValue('C1', '产品中文名')
->setCellValue('D1', '产品英文名')
->setCellValue('E1', '链接');
$criteria = $this->searchCriteriaBuilder->addFilter(
$this->filterBuilder->setField('type_id')->setValue('configurable')->create()
)
->addFilter(
$this->filterBuilder->setField('status')->setValue(1)->create()
)
// ->addFilter(
// $this->filterBuilder->setField('search_words')->setConditionType('notnull')->create()
// )
->create();
$sheet->getRowDimension(1)->setRowHeight(20);
$key = 2;
foreach ($this->productRepository->getList($criteria)->getItems() as $item) {
if (!str_contains($item->getSku(), '_C')) {
continue;
}
$categories = $item->getCategoryIds();
$catIds = (int)end($categories);
if (count($categories) > 3) {
$catIds = $categories[2];
}
$sheet->getRowDimension($key)->setRowHeight(20);
$sheet->setCellValue('A'.$key, $item->getSku())
->setCellValue('B'.$key, $this->getCategory($catIds))
->setCellValue('C'.$key, $item->getName())
->setCellValue('D'.$key, $item->getSearchWords())
->setCellValue('E'.$key, $this->productHelper->getProductUrl($item));
$key++;
}
$writer = IOFactory::createWriter($spreadsheet, IOFactory::READER_XLSX);
$writer->save($filePath);
return 1;
}
}
@@ -0,0 +1,162 @@
<?php
namespace Stemcell\Catalog\Console\Command;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\State;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\UrlInterface;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Exception;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
/**
* 更新产品详情的产品说明书及文档中PDF的URL,如果PDF在服务器上存在,就用当前域名替换pdf的域名。
*/
class ProtocolsDocumentationPdfUpdate extends Command
{
private OutputInterface $output;
private string $baseUrl;
private array $notExistPdf = [];
public function __construct(
private ProductCollection $productCollection,
private DirectoryList $directoryList,
private UrlInterface $url,
private ProductRepository $productRepository,
private State $state,
private \Magento\Store\Model\StoreManagerInterface $storeManager,
) {
parent::__construct('protocols:documentation:update');
}
protected function updatePdfUrl(Product $product){
$html = $product->getData('protocols_documentation');
$html = preg_replace('/<\/?body[^>]*>/i', '', $html);
$dom = new \DOMDocument();
libxml_use_internal_errors(true); // 避免 HTML 解析警告
$dom->loadHTML(mb_encode_numericentity($html, [0x80, 0x10FFFF, 0, ~0], 'UTF-8'));
libxml_clear_errors();
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
$href = $link->getAttribute('href');
// $output->writeln('old pdf href: ' . $href);
if ($href && preg_match('/\.pdf$/i', $href)) {
$pdfPath = parse_url($href, PHP_URL_PATH);
$pdfPath = $this->directoryList->getPath(DirectoryList::PUB).'/'.$pdfPath;
// 检查 PDF 是否存在
if (file_exists($pdfPath)) {
$this->output->writeln(sprintf('product %s old pdf href: %s', $product->getSku(), $href));
$newUrl = preg_replace(
'#^https?://[^/]+/#i',
$this->baseUrl,
$href
);
$this->output->writeln(sprintf('<info>product %s updated pdf href: %s</info>', $product->getSku(), $newUrl));
// 更新 <a> 标签的 href
$link->setAttribute('href', $newUrl);
} else {
$md5 = md5(strtolower($href));
if (!isset($this->notExistPdf[$md5])) {
$this->notExistPdf[$md5] = $href;
}
}
}
}
$body = $dom->getElementsByTagName("body")->item(0);
return $dom->saveHTML($body);
}
/**
* @throws Exception
* @throws FileSystemException
*/
protected function exportNotExistPdf()
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle('A1:' . 'B1')->getFont()->setBold(true);
$sheet->setCellValue('A1', 'pdf links');
$rowIndex = 2;
foreach ($this->notExistPdf as $link) {
// $sheet->setCellValue('B' . $rowIndex, implode("\n", $links));
$sheet->getStyle('A' . $rowIndex)->getAlignment()->setWrapText(true);
$sheet->setCellValueExplicit('A' . $rowIndex, $link, DataType::TYPE_STRING);
$sheet->getColumnDimension('A')->setWidth(100);
$rowIndex++;
}
$writer = new Xlsx($spreadsheet);
$pdfPath = $this->directoryList->getPath(DirectoryList::VAR_DIR).'/share/产品说明书及文档不存在的PDF-'.date('Ymd').'.xlsx';
$writer->save($pdfPath);
}
public function execute(InputInterface $input, OutputInterface $output)
{
$this->state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
$this->output = $output;
$this->baseUrl = $this->url->getBaseUrl();
foreach ($this->storeManager->getStores(true) as $store) {
$collection = $this->productCollection
->setStoreId($store->getId())
->addAttributeToFilter('protocols_documentation', ['neq' => 'NULL']);
foreach ($collection as $product) {
// if ($product->getSku()=='100-0237_C') {
// $output->writeln(preg_replace('/<\/?body[^>]*>/i', '', $product->getData('protocols_documentation')));
// } else {
// continue;
// }
$output->writeln(sprintf('product: %s', $product->getSku()));
$html = preg_replace('/<\/?body[^>]*>/i', '', $this->updatePdfUrl($product));
// $output->writeln('updated html: ');
// $output->writeln($html);
// $output->writeln('');
$product->setData('protocols_documentation', $html);
try {
$product->setData('_edit_mode', true);
$product->setStoreId($store->getId());
$this->productRepository->save($product);
} catch (\Exception $e) {
$this->output->writeln(sprintf('<error>product %s updated pdf fail, msg: %s</error>', $product->getSku(), $e->getMessage()));
}
// if ($product->getSku()=='100-0237_C') {
// break;
// }
}
}
$this->exportNotExistPdf();
return Command::SUCCESS;
}
}
@@ -0,0 +1,65 @@
<?php
namespace Stemcell\Catalog\Console\Command;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\State;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\StateException;
use Symfony\Component\Console\Command\Command;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ProtocolsDocumentationRepair extends Command
{
public function __construct(
private ProductCollectionFactory $productCollectionFactory,
private ProductRepository $productRepository,
private State $state,
)
{
parent::__construct('protocols:documentation:repair');
}
public function execute(InputInterface $input, OutputInterface $output)
{
$this->state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
$store0Collection = $this->productCollectionFactory->create()
->setStoreId(0)
->addAttributeToFilter('protocols_documentation', ['neq' => 'NULL'])
->load();
$store1Collection = $this->productCollectionFactory->create()
->setStoreId(1)
->addAttributeToFilter('protocols_documentation', ['neq' => 'NULL'])
->load();
foreach ($store1Collection as $item) {
/* @var $item \Magento\Catalog\Model\Product */
/* @var $product \Magento\Catalog\Model\Product */
$product = $store0Collection->getItemById($item->getId());
$output->writeln('store 1 product: '. $item->getSku());
$output->writeln('store 0 product: '. $product->getSku());
$output->writeln('');
// $output->writeln('store 1 protocols_documentation:');
// $output->writeln($item->getData('protocols_documentation'));
//
// $output->writeln('store 0 protocols_documentation:');
// $output->writeln($product->getData('protocols_documentation'));
$item->setData('protocols_documentation', $product->getData('protocols_documentation'));
$item->setData('_edit_mode', true);
try {
$this->productRepository->save($item);
} catch (\Exception $e) {
$output->writeln('product: '.$item->getSku().'exception: <error> '.$e->getMessage().'</error>');
}
}
return Command::SUCCESS;
}
}
@@ -0,0 +1,86 @@
<?php
namespace Stemcell\Catalog\Console\Command;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Module\Dir;
use Stemcell\Catalog\Model\CryopreserveFactory;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
* 从excel中导入数据
*/
class SampleCryopreserveImport extends Command
{
protected $parentProduct = [];
/**
* @var ResourceConnection
*/
private $resource;
public function __construct(
private Dir $dir,
private CryopreserveFactory $cryopreserveFactory,
ResourceConnection $resource,
){
parent::__construct('sample:cryopreserve:import');
$this->setDescription('样本冻存参考小工具数据导入');
$this->resource = $resource;
}
protected function getSpreadsheet()
{
$path = $this->dir->getDir('Stemcell_Catalog').'/data/sample-cryopreserve.xlsx';
if (!file_exists($path)) {
throw new \Exception(sprintf('File %s does not exist', $path));
}
return IOFactory::load($path);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
//删除旧数据
$connection = $this->resource->getConnection()->query('TRUNCATE TABLE cryopreserve');
$spreadsheet = $this->getSpreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$lastRow = $sheet->getHighestRow();
for ($row = 2; $row <= $lastRow; ++$row) {
$sample = $sheet->getCell('A' . $row)->getValue();
if ($sample) {
$sample = trim($sample);
} else {
break;
}
$type = trim((string)$sheet->getCell('B' . $row)->getValue());
$cellType = $sheet->getCell('C' . $row)->getValue();
if ($cellType) {
$cellType = trim($cellType);
}
$referenceDensity = $sheet->getCell('D' . $row)->getValue();
$desc = $sheet->getCell('E' . $row)->getValue();
if ($desc) {
$desc = str_replace("\n", '<br/>', $desc);
}
$references = [];
foreach (explode("\n", (string)$sheet->getCell('F' . $row)->getValue()) as $reference) {
$references[] = preg_replace('/\d+[\.\。]\s+/', '', $reference);
}
$data = [
'sample'=>$sample, 'type'=>$type, 'cell_type'=>$cellType,
'reference_density'=>$referenceDensity, 'desc'=>$desc, 'reference'=>json_encode($references)
];
$this->cryopreserveFactory->create()->setData($data)->save();
}
return 0;
}
}
@@ -0,0 +1,118 @@
<?php
namespace Stemcell\Catalog\Console\Command;
use LanguageDetector\LanguageDetector;
use Magento\Catalog\Model\ProductRepository;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Framework\App\Config\Storage\WriterInterface as ConfigWriter;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\State;
use Magento\Framework\Filesystem\DirectoryList;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
use phpseclib3\Crypt\Common\SymmetricKey;
use Stemcell\Datacollection\Cron\FormRecordsNotification;
use Stemcell\ProductImport\Console\Command\ExtractDescriptionFromProductDataCSV;
use Stemcell\ProductImport\Cron\ImportPrice;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use phpseclib3\Crypt\AES;
use phpseclib3\Crypt\Common\BlockCipher;
use Magento\Framework\App\Cache\TypeListInterface;
class Test extends Command
{
const NO_PRICE_SKU_PATH = 'catalog/product_settings/no_price_sku';
public function __construct(
private FormRecordsNotification $formRecordsNotification,
private DirectoryList $directoryList,
protected ImportPrice $importStock,
protected ConfigWriter $configWriter,
protected TypeListInterface $cacheTypeList,
protected TimezoneInterface $timezone,
protected FilterProvider $filterProvider,
protected StoreManagerInterface $storeManager,
protected ProductRepository $productRepository,
protected State $state
)
{
$name = 'test';
parent::__construct($name);
}
public function getMediaUrl()
{
return $this->storeManager
->getStore()
->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
}
protected function isDirEmpty($dir) {
if (!is_dir($dir)) {
return false; // 或者抛出异常
}
$files = scandir($dir);
// 减去 . 和 .. 后,如果数量为0,则文件夹为空
return count($files) == 2; // 2 表示只有 . 和 ..
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// $this->formRecordsNotification->execute();
// $output->writeln($this->directoryList->getPath('media'));
// $content = "Hello world !";
// $ivStr128 = "1234567812345678"; // 16字节
// $AESSecretGCM256 = "IhHEhIvTS8zbVTY391GP8oHJ7RmSJ8pQ"; // 32字节
// $output->writeln(self::encryptGCMWithPhpseclib($content, $AESSecretGCM256, $ivStr128));
// $output->writeln($this->timezone->date()->format('Y-m-d H:i:s'));
$this->state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
$product = $this->productRepository->get('MRDX20359', true);
$existingEntries = $product->getMediaGalleryEntries();
if (!empty($existingEntries)) {
$output->writeln(" 清理现有图片,共 " . count($existingEntries) . " 张");
// 清空媒体库条目
$product->setMediaGalleryEntries([]);
// 清除图片角色
$product->setImage(null);
$product->setSmallImage(null);
$product->setThumbnail(null);
$this->productRepository->save($product);
// $output->writeln(" 现有图片清理完成");
}
// $this->configWriter->save(
// self::NO_PRICE_SKU_PATH,
// '111111111111111111111',
// ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
// 0
// );
// $this->cacheTypeList->cleanType('config');
// $this->importStock->execute();
return Command::SUCCESS;
}
public static function encryptGCMWithPhpseclib($content, $key, $iv)
{
$cipher = new AES('gcm');
$cipher->setPreferredEngine(SymmetricKey::ENGINE_OPENSSL_GCM);
$cipher->setKey($key);
$cipher->setNonce($iv);
$cipher->setKeyLength(256); // 尝试设置256位标签
$cipherText = $cipher->encrypt($content);
$tag = $cipher->getTag();
// 打包数据
$ivLength = pack('N', strlen($iv));
$byteBuffer = $ivLength . $iv . $cipherText . $tag;
return base64_encode($byteBuffer);
}
}