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,150 @@
<?php
namespace Stemcell\Catalog\Model\Api;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type as ProductType;
use Magento\Framework\Module\Dir;
use Magento\Framework\UrlInterface;
use Magento\Framework\Webapi\Rest\Request;
use Magento\Store\Model\StoreManagerInterface;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Stemcell\Catalog\Helper\Excel;
use Magento\Eav\Model\Config as EavConfig;
use Stemcell\Catalog\Setup\Patch\Data\AddChineseEditionCellSeparationOption;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
/**
* 分选说明书接口
*/
class CellSeparation
{
public function __construct(
private Dir $dir,
private StoreManagerInterface $storeManager,
private Request $restRequest,
protected EavConfig $eavConfig,
protected ProductCollectionFactory $productCollectionFactory,
) {
}
/**
* @param Worksheet $sheet
* @param string $cell
* @return string
*/
protected function getCellValue(Worksheet $sheet, string $cell)
{
return trim((string)$sheet->getCell($cell)->getValue());
}
/**
* @return int
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function getResourceTypeChinesePisOptionId()
{
$attribute = $this->eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, 'resource_type');
$attribute->setStoreId(0);
$optionId = 0;
foreach ($attribute->getOptions() as $option) {
if ($option->getLabel() == AddChineseEditionCellSeparationOption::RESOURCE_TYPE_ENGLISH_LABEL) {
$optionId = (int)$option->getValue();
break;
}
}
return $optionId;
}
/**
* 分选说明书接口
* @return string
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @throws \Exception
*/
public function execute()
{
$pageSize = 10;
$page = $this->restRequest->getParam('page', 1);
$start = ($page - 1) * $pageSize;
$keyword = trim($this->restRequest->getParam('keyword', ''));
$isSku = preg_match('/^\d+[A-Za-z]*$/', $keyword) !==0 ;
//['sku' => $sku, 'label' => $name, 'pdf'=>$mediaUrl.$pdfPath, 'url'=>$mediaUrl.$sku.'/'.$pdfPath]
$data = [];
$mediaUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_WEB);
$chinesePisCollection = $this->productCollectionFactory->create()
->addAttributeToSelect(['parent_skus', 'document_path', 'parent_names'])
->addAttributeToFilter('status', Status::STATUS_ENABLED)
->addAttributeToFilter('type_id', ProductType::TYPE_VIRTUAL)
->addAttributeToFilter('resource_type', $this->getResourceTypeChinesePisOptionId());
if ($keyword) {
$chinesePisCollection->addAttributeToFilter([
['attribute' => 'parent_skus', 'finset' => $keyword],
['attribute' => 'parent_names', 'like' => '%'.$keyword.'%'],
]);
}
$parentSkus = '';
foreach ($chinesePisCollection as $item) {
$parentSkus .= $item->getData('parent_skus').',';
}
$parentSkus = trim($parentSkus, ',');
$productNames = [];
$collection = $this->productCollectionFactory->create()
->addAttributeToSelect(['name'])
->addAttributeToFilter('status', Status::STATUS_ENABLED)
->addAttributeToFilter('sku', ['in' => array_unique(explode(',', $parentSkus))]);
foreach ($collection as $item) {
$productNames[$item->getSku()] = $item->getName();
}
foreach ($chinesePisCollection as $item) {
$pdfPath = $mediaUrl.ltrim($item->getData('document_path'), '/');
if ($item->getData('parent_skus')) {
foreach (explode(',', $item->getData('parent_skus')) as $sku) {
if (($isSku && $keyword && $sku && strtolower($keyword)==strtolower($sku))
|| (!$isSku && $item->getData('parent_names') && str_contains(strtolower($item->getData('parent_names')), strtolower($keyword)))) {
if (isset($productNames[$sku])){
$data[$item->getSku()] = [
'sku' => $sku,
'label' => $productNames[$sku],
'pdf'=>ltrim($pdfPath, '/'),
'url'=>ltrim($pdfPath, '/')
];
}
}
}
}
}
$data = array_values($data);
$count = count($data);
// $pages = ceil($count / $pageSize);
// $page = min($page, $pages);
// $end = $page * $pageSize - 1;
// $rows = [];
// foreach ($data as $index => $row) {
// if ($index >= $start && $index <= $end) {
// $rows[] = $row;
// }
// if ($index > $end) {
// break;
// }
// }
$result = [
'items' => $data,
'filter_code' => 'keyword',
'filters' => [],
'pages' => $page,
'total_count' => $count,
];
return json_encode($result);
}
}
@@ -0,0 +1,188 @@
<?php
namespace Stemcell\Catalog\Model\Api;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Webapi\Rest\Request as RestRequest;
use Stemcell\Catalog\Api\Data\CellSortSearchResultsInterface;
use Stemcell\Catalog\Model\ResourceModel\CellSort\Collection as CellSortCollection;
use Stemcell\Catalog\Model\ResourceModel\CellSort\CollectionFactory as CellSortCollectionFactory;
use Stemcell\Catalog\Model\ResourceModel\Species\Collection as SpeciesCollection;
use Stemcell\Catalog\Model\ResourceModel\CellType\Collection as CellTypeCollection;
use Stemcell\Catalog\Model\ResourceModel\CellSubType\Collection as CellSubTypeCollection;
use Stemcell\Catalog\Model\ResourceModel\Tissue\Collection as TissueCollection;
/**
* 此接口依赖cell:sort:import命令和app/code/Stemcell/Catalog/data/cell-select-tool.xlsx。
* 如果ell-select-tool.xlsx中的数据有改动,就需要重新跑cell:sort:import命令
*/
class CellSortTool
{
protected array $labels = [
'species' => '物种',
'cellTypes' => '细胞',
'cellSubTypes' => '细胞亚型',
'tissues' => '样本',
];
public function __construct(
private CellSortCollection $cellSortCollection,
private CellSortCollectionFactory $cellSortCollectionFactory,
private RestRequest $restRequest,
private ProductRepositoryInterface $productRepository,
private CellSortSearchResultsInterface $cellSortSearchResults,
private SearchCriteriaBuilder $searchCriteriaBuilder,
private SpeciesCollection $speciesCollection,
private CellTypeCollection $cellTypeCollection,
private CellSubTypeCollection $cellSubTypeCollection,
private TissueCollection $tissueCollection,
) {
}
protected function addFilter()
{
$species = intval($this->restRequest->getParam('species'));
$cellTypeId = intval($this->restRequest->getParam('cellTypes'));
$cellSubTypeId = intval($this->restRequest->getParam('cellSubTypes'));
$tissueId = intval($this->restRequest->getParam('tissues'));
if ($species) {
$this->cellSortCollection->addFieldToFilter('species_id', $species);
}
if ($cellTypeId) {
$this->cellSortCollection->addFieldToFilter('cell_type_id', $cellTypeId);
}
if ($cellSubTypeId) {
$this->cellSortCollection->addFieldToFilter('cell_subtype_id', $cellSubTypeId);
}
if ($tissueId) {
$this->cellSortCollection->addFieldToFilter('tissue_id', $tissueId);
}
}
protected function getSpecies()
{
$species = [];
$items = $this->speciesCollection->setOrder('species_sort', 'asc')->load()->getItems();
foreach ($items as $specie) {
/* @var $specie \Stemcell\Catalog\Model\Species */
$species[$specie->getSpeciesId()] = $specie->toArray();
}
return $species;
}
protected function getCellTypes()
{
$speciesId = intval($this->restRequest->getParam('species'));
$data = [];
if ($speciesId) {
$cellTypes = $this->cellSortCollectionFactory->create()->addFieldToFilter('species_id', $speciesId)->setOrder('cell_type_sort', 'asc');
foreach ($cellTypes as $cellType) {
/* @var $cellType \Stemcell\Catalog\Model\CellSort */
if (!isset($data[$cellType->getCellTypeId()])) {
$data[$cellType->getCellTypeId()] = ['cell_type_id' => $cellType->getCellTypeId(), 'cell_type_name' => $cellType->getCellTypeName(), 'cell_type_sort'=>$cellType->getData('cell_type_sort')];
}
}
} else {
$data = $this->cellTypeCollection->setOrder('cell_type_sort', 'asc')->load()->getData();
}
return array_values($data);
}
protected function getCellSubTypes()
{
$cellTypesId = intval($this->restRequest->getParam('cellTypes'));
$speciesId = intval($this->restRequest->getParam('species'));
$data = [];
if ($cellTypesId) {
$cellTypes = $this->cellSortCollectionFactory->create()
->addFieldToFilter('species_id', $speciesId)
->addFieldToFilter('cell_type_id', $cellTypesId)
->setOrder('cell_subtype_sort', 'asc');
foreach ($cellTypes as $cellType) {
/* @var $cellType \Stemcell\Catalog\Model\CellSort */
if (!isset($data[$cellType->getCellSubTypeId()])) {
$data[$cellType->getCellSubTypeId()] = ['cell_subtype_id' => $cellType->getCellSubTypeId(), 'cell_subtype_name' => $cellType->getCellSubTypeName()];
}
}
} else {
$data = $this->cellSubTypeCollection->setOrder('cell_subtype_sort', 'asc')->load()->getData();
}
return array_values($data);
}
protected function getTissues()
{
$cellTypesId = intval($this->restRequest->getParam('cellTypes'));
$speciesId = intval($this->restRequest->getParam('species'));
$cellSubTypeId = intval($this->restRequest->getParam('cellSubTypes'));
$data = [];
if ($cellSubTypeId) {
$cellTypes = $this->cellSortCollectionFactory->create()
->addFieldToFilter('species_id', $speciesId)
->addFieldToFilter('cell_type_id', $cellTypesId)
->addFieldToFilter('cell_subtype_id', $cellSubTypeId);
foreach ($cellTypes as $cellType) {
/* @var $cellType \Stemcell\Catalog\Model\CellSort */
if (!isset($data[$cellType->getTissueId()])) {
$data[$cellType->getTissueId()] = ['tissue_id' => $cellType->getTissueId(), 'tissue_name' => $cellType->getTissueName()];
}
}
} else {
$data = $this->tissueCollection->load()->getData();
}
return array_values($data);
}
/**
* @return array[]
*/
private function getFilters()
{
$species = $this->getSpecies();
return ['species' => array_values($species), 'cellTypes' => $this->getCellTypes(), 'cellSubTypes' => $this->getCellSubTypes(), 'tissues' => $this->getTissues()];
}
/**
* @return \Stemcell\Catalog\Api\Data\CellSortSearchResultsInterface
*/
public function getProducts() {
$this->addFilter();
$skus = $flags = [];
foreach ($this->cellSortCollection as $cellSort) {
/* @var $cellSort \Stemcell\Catalog\Model\CellSort */
if (!isset($skus[$cellSort->getSku()])) {
$skus[$cellSort->getSku()] = $cellSort->getSku();
}
if (!isset($flags[$cellSort->getSku()])) {
$flags[$cellSort->getSku()] = $cellSort->getFlag();
}
}
$pageSize = 10;
$page = intval($this->restRequest->getParam('page'));
$criteria = $this->searchCriteriaBuilder
->addFilter('sku', $skus, 'in')
->addFilter('visibility', [2,3,4], 'in')
->setPageSize($pageSize)
->setCurrentPage($page)
->create();
$products = $this->productRepository->getList($criteria);
foreach ($products->getItems() as $product) {
$sku = $product->getSku();
$product->getExtensionAttributes()?->setCellFlag(isset($flags[$sku]) && $flags[$sku]==1? true:false);
}
return $this->cellSortSearchResults->setFilters(json_encode($this->getFilters()))
->setLabels(json_encode($this->labels))
->setItems($products->getItems())
->setTotalCount($products->getTotalCount());
}
}
@@ -0,0 +1,42 @@
<?php
namespace Stemcell\Catalog\Model\Api\Data;
use Magento\Framework\Api\SearchResults;
use Stemcell\Catalog\Api\Data\CellSortSearchResultsInterface;
class CellSortSearchResults extends SearchResults implements CellSortSearchResultsInterface
{
/**
* @inheritDoc
*/
public function getFilters()
{
return $this->_get(self::FILTERS);
}
/**
* @inheritDoc
*/
public function setFilters(string $filters)
{
return $this->setData(self::FILTERS, $filters);
}
/**
* @inheritDoc
*/
public function getLabels()
{
return $this->_get(self::LABELS);
}
/**
* @inheritDoc
*/
public function setLabels(string $labels)
{
return $this->setData(self::LABELS, $labels);
}
}
@@ -0,0 +1,52 @@
<?php
namespace Stemcell\Catalog\Model\Api\Data;
use Stemcell\Catalog\Api\Data\ProductListWithFilterInterface;
use Magento\Framework\Api\SearchResults;
class ProductListWithFilter extends SearchResults implements ProductListWithFilterInterface
{
const FILTERS = 'filters';
const FILTER_CODE = 'filterCode';
/**
* @param string $filter
* @return $this
*/
public function setFilters(string $filter)
{
$this->setData(self::FILTERS, $filter);
return $this;
}
/**
* @return string
*/
public function getFilters()
{
if (empty($this->_get(self::FILTERS))) {
$this->setData(self::FILTERS, []);
}
return $this->_get(self::FILTERS);
}
/**
* @param string $filterCode
* @return $this
*/
public function setFilterCode(string $filterCode)
{
$this->setData(self::FILTER_CODE, $filterCode);
return $this;
}
/**
* @return string
*/
public function getFilterCode()
{
return (string)$this->_get(self::FILTER_CODE);
}
}
@@ -0,0 +1,61 @@
<?php
namespace Stemcell\Catalog\Model\Api;
use Magento\Framework\Webapi\Rest\Request as RestRequest;
use Magento\Store\Model\StoreManagerInterface;
use Stemcell\Catalog\Model\ResourceModel\ExperimentalScheme\CollectionFactory as CollectionFactory;
/**
* 实验方案
*/
class ExperimentalScheme
{
const PAGE_SIZE = 10;
public function __construct(
private RestRequest $restRequest,
private CollectionFactory $collectionFactory,
private StoreManagerInterface $storeManager,
) {
}
protected function getFilters() : array
{
$collection = $this->collectionFactory->create();
$table = $collection->getMainTable();
$rows = $collection->getConnection()->fetchAll(
'select MIN(collection_name) AS collection_name, collection_sort from '.$table
.' group by collection_sort order by collection_sort asc'
);
$data = [];
foreach ($rows as $row) {
$data[] = ['collection_name'=>$row['collection_name']];
}
return array_values($data);
}
/**
* @return string
*/
public function execute()
{
$collectionName = trim((string)$this->restRequest->getParam('collection'));
$page = intval($this->restRequest->getParam('page', 1));
$collection = $this->collectionFactory->create();
if (!empty($collectionName)) {
$collection->addFieldToFilter('collection_name', $collectionName);
}
$collection->setPageSize(self::PAGE_SIZE)->setCurPage($page)->setOrder('collection_sort', 'asc');
$mediaUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$data = $collection->getData();
foreach ($data as &$item) {
$item['image'] = $mediaUrl . $item['image'];
}
return json_encode([
'data'=>['items' => $data, 'total_count'=>$collection->getSize()],
'filters' => ['collection'=>$this->getFilters()]
]);
}
}
@@ -0,0 +1,387 @@
<?php
namespace Stemcell\Catalog\Model\Api;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Layer\Category as CategoryLayer;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\SortOrder;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\Api\Search\SearchInterface;
use \Magento\Framework\Api\Search\SearchCriteriaInterface;
use Magento\Framework\Api\Search\FilterGroupBuilder;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Module\Dir;
use Magento\Framework\Webapi\Rest\Request;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use Psr\Log\LoggerInterface;
use Stemcell\Catalog\Helper\Configuration as ConfigurationHelper;
use Magento\Eav\Model\Config as EavConfig;
use Stemcell\Catalog\Api\Data\ProductListWithFilterInterface;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
use Magento\Store\Model\StoreManagerInterface;
use Stemcell\Catalog\Helper\Excel;
use \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Stemcell\Catalog\Model\ProductManualSearch;
use Stemcell\Catalog\Setup\Patch\Data\AddChineseEditionCellSeparationOption;
class Product
{
private CategoryLayer $_categoryLayer;
private array $filters = [
'e-book' => ['attribute' => 'area_of_interest', 'optionsLabel' => ['免疫', '嵌合体', '类器官', '脐带血库', 'HLA']],
'product-information-sheets' => ['attribute' => 'resource_type', 'optionsLabel' => ['产品信息表', '技术手册']],
'protocol' => ['attribute' => 'area_of_interest', 'optionsLabel' =>
[
'上皮细胞研究', '免疫', '内皮细胞研究', '呼吸系统研究', '干细胞生物学', '感染性疾病(传染病)', '疾病建模', '癌症',
'神经科学', '类器官', '细胞治疗开发', '细胞系制备', '药物发现和毒理检测'
]
],
'product-manual' => ['attribute' => 'area_of_interest', 'optionsLabel' =>
[
'HIV', '上皮细胞研究', '免疫', '内皮细胞研究', '呼吸系统研究', '嵌合体', '干细胞生物学', '感染性疾病(传染病)',
'抗体制备', '杂交瘤制备', '疾病建模', '癌症', '神经科学', '移植研究', '类器官', '细胞治疗开发', '细胞系制备',
'脐带血库', '药物发现和毒理检测', '血管生成细胞研究', 'HLA'
]
]
];
public function __construct(
private ProductRepositoryInterface $productRepository,
private SearchCriteriaBuilder $searchCriteriaBuilder,
private FilterBuilder $filterBuilder,
private SearchInterface $search,
private SearchCriteriaInterface $searchCriteria,
private FilterGroupBuilder $filterGroupBuilder,
private ConfigurationHelper $configurationHelper,
private SortOrder $sortOrder,
private Resolver $layerResolver,
private Request $restRequest,
private EavConfig $eavConfig,
private ProductListWithFilterInterface $productListWithFilter,
private ProductCollectionFactory $productCollectionFactory,
private Dir $dir,
private StoreManagerInterface $storeManager,
private ProductManualSearch $productManualSearch,
) {
}
/**
* @param int $categoryId
* @param int $page
* @return \Magento\Catalog\Api\Data\ProductSearchResultsInterface
*/
public function getList(int $categoryId, int $page = 1)
{
$statusFilter = $this->filterBuilder
->setField('status')
->setConditionType('eq')
->setValue(1)
->create();
$visibilityFilter = $this->filterBuilder
->setField('visibility')
->setConditionType('in')
->setValue([2,3,4])
->create();
$categoryFilter = $this->filterBuilder
->setField('category_id')
->setConditionType('eq')
->setValue($categoryId)
->create();
$criteria = $this->searchCriteriaBuilder
->addFilters([$visibilityFilter, $categoryFilter])
->setPageSize(10)
->setCurrentPage($page)
->addSortOrder($this->sortOrder->setField('entity_id')->setDirection('DESC'))
->create();
return $this->productRepository->getList($criteria);
}
/**
* @param string $sku
* @return \Magento\Catalog\Api\Data\ProductInterface|void
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getBySku(string $sku){
$product = $this->productRepository->get($sku);
if ($product->getTypeId() == Configurable::TYPE_CODE) {
$attributes = $this->configurationHelper->getConfigurableAttributeProducts($product);
/* @var $productTypeInstance \Magento\ConfigurableProduct\Model\Product\Type\Configurable */
$productTypeInstance = $product->getTypeInstance();
$configurableAttributes = $productTypeInstance->getConfigurableAttributesAsArray($product);
foreach ($product->getExtensionAttributes()->getConfigurableProductOptions() as $option) {
$options = array_column($option->getOptions(), null, 'value_index');
if (isset($configurableAttributes[$option->getAttributeId()])) {
$option->setLabel($configurableAttributes[$option->getAttributeId()]['frontend_label']);
}
foreach ($option->getValues() as $value) {
if (isset($options[$value->getValueIndex()])) {
$value->getExtensionAttributes()
->setLabel($options[$value->getValueIndex()]['label'])
->setProducts($attributes[$option->getAttributeId()][$value->getValueIndex()]??[]);
}
}
}
list($childrenImages, $childrenDescription) = $this->configurationHelper->getOptionImages($product);
$product->getExtensionAttributes()
->setChildrenImages(json_encode($childrenImages))
->setChildrenShortDescription(json_encode($childrenDescription));
}
return $product;
}
/**
* @param string $term
* @param int $page
* @return \Magento\Catalog\Api\Data\ProductSearchResultsInterface
*/
public function search(string $term, int $page = 1)
{
$pageSize = 10;
$termFilter = $this->filterBuilder
->setField('search_term')
->setValue($term)
->setConditionType('like')
->create();
$criteria = $this->searchCriteria
->setFilterGroups([$this->filterGroupBuilder->addFilter($termFilter)->create()])
->setRequestName('quick_search_container');
$result = $this->search->search($criteria);
$productIds = [];
foreach ($result->getItems() as $product) {
/* @var $product \Magento\Framework\Api\Search\Document */
if ($product->getCustomAttribute('score')->getValue() < 10) {
continue;
}
$productIds[] = $product->getId();
}
$filter = $this->filterBuilder
->setField('entity_id')
->setConditionType('in')
->setValue(array_values($productIds))
->create();
$criteria = $this->searchCriteriaBuilder
->addFilters([$filter])
->setPageSize($pageSize)
->setCurrentPage($page)
->create();
return $this->productRepository->getList($criteria);
}
protected function getProductOptions(string $attribute, array $optionsLabel)
{
$attribute = $this->eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attribute);
$options = [];
foreach ($attribute->getSource()->getAllOptions() as $option) {
if (in_array($option['label'], $optionsLabel)) {
$options[] = $option;
}
}
return [$options, $attribute->getFrontendInput() == 'multiselect'];
}
/**
* 根据产品说明书分类下的产品parent_skus, 获取对应产品的name、sku,通过parents返回给前端显示
* @param ProductCollection $productCollection
* @return void
*/
protected function setParent(ProductCollection $productCollection)
{
foreach ($productCollection as $product) {
/* @var $product \Magento\Catalog\Api\Data\ProductInterface */
if ($parentSkus = $product->getData('parent_skus')) {
$collection = $this->productCollectionFactory->create()->addAttributeToSelect('name')
->addAttributeToFilter('sku', ['in' => explode(',', $parentSkus)]);
$parents = [];
foreach ($collection as $item) {
$parents[] = ['sku' => $item->getSku(), 'name' => $item->getName()];
}
$product->getExtensionAttributes()->setParents(json_encode($parents));
}
}
}
/**
* @return int
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function getResourceTypeChinesePisOptionId()
{
$attribute = $this->eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, 'resource_type');
$attribute->setStoreId(0);
$optionId = 0;
foreach ($attribute->getOptions() as $option) {
if ($option->getLabel() == AddChineseEditionCellSeparationOption::RESOURCE_TYPE_ENGLISH_LABEL) {
$optionId = (int)$option->getValue();
break;
}
}
return $optionId;
}
/**
* 小程序技术资源
* @param int $categoryId
* @param string $type
* @param int $page
* @return ProductListWithFilterInterface
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function categoryProduct(int $categoryId, $type = 'e-book', int $page = 1)
{
$pageSize = 10;
$attribute = $this->filters[$type]['attribute'];
$this->_categoryLayer = $this->layerResolver->get();
$this->_categoryLayer->setCurrentCategory($categoryId);
$this->_categoryLayer->apply();
$collection = $this->_categoryLayer->getProductCollection();
list($filters, $isMultiselect) = $this->getProductOptions($attribute, $this->filters[$type]['optionsLabel']);
if ($this->restRequest->getParam($attribute)) {
if ($isMultiselect) {
$collection->addAttributeToFilter($attribute, ['finset' => explode(',', trim($this->restRequest->getParam($attribute)))]);
} else {
$collection->addAttributeToFilter($attribute, trim($this->restRequest->getParam($attribute)));
}
}
$collection->addAttributeToSelect('*')->setOrder('position', 'asc')
->addAttributeToFilter('visibility', ['in' => [2,3,4]]);
if ($type == 'product-information-sheets') {
$collection->addAttributeToFilter('parent_skus', array('notnull' => true) )
->addAttributeToFilter('parent_names', array('notnull' => true) )
->addAttributeToFilter('resource_type', ['neq' => $this->getResourceTypeChinesePisOptionId()]);
$keyword = $this->restRequest->getParam('keyword');
if ($keyword) {
$collection->addAttributeToFilter([
['attribute' => 'parent_skus', 'like' => '%' . $keyword . '%'],
['attribute' => 'parent_names', 'like' => '%' . $keyword . '%'],
]);
}
$logger = ObjectManager::getInstance()->get(LoggerInterface::class);
$logger->info($collection->getSelectSql(true));
}
$collection->setPage($page, $pageSize);
$this->setParent($collection);
return $this->productListWithFilter->setFilters(json_encode($filters))
->setItems($collection->getItems())
->setTotalCount($collection->getSize())
->setFilterCode($attribute);
}
/**
* 实验方案
* @return string
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function experimentalScheme()
{
$path = $this->dir->getDir('Stemcell_Catalog').'/data/experimental-scheme.csv';
$file = fopen($path, "r");
$data = [];
$mediaUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
while (($row = fgetcsv($file)) !== FALSE) {
if (isset($row[1])) {
$row[0] = preg_replace('/^\xEF\xBB\xBF/', '', $row[0]);
$data[$row[0]]['label'] = $row[0];
$data[$row[0]]['list'][] = ['label' => $row[1], 'url' => $row[2], 'image'=>$mediaUrl.$row[3]];
}
}
return json_encode(array_values($data));
}
/**
* @param Worksheet $sheet
* @param string $cell
* @return string
*/
protected function getCellValue(Worksheet $sheet, string $cell)
{
return trim((string)$sheet->getCell($cell)->getValue());
}
/**
* 产品手册接口
* @return string
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function productManual()
{
$path = $this->dir->getDir('Stemcell_Catalog').'/data/product-manual.xlsx';
$data = [];
$sheet = Excel::getExcelSheet($path);
$mediaUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
foreach ($sheet->getRowIterator() as $row) {
if ($row->getRowIndex() == 1) {
continue;
}
$researchFiled = $this->getCellValue($sheet, 'A'.$row->getRowIndex());
$name = $this->getCellValue($sheet, 'B'.$row->getRowIndex());
$imagePath = $this->getCellValue($sheet, 'C'.$row->getRowIndex());
$pdfPath = $this->getCellValue($sheet, 'D'.$row->getRowIndex());
if (!empty($name)) {
$data[$researchFiled]['label'] = $researchFiled;
$data[$researchFiled]['list'][] = ['label' => $name, 'url' => $mediaUrl.$imagePath, 'pdf'=>$mediaUrl.$pdfPath];
}
}
return json_encode(array_values($data));
}
/**
* 操作视频
* @return string
*/
public function videos()
{
$path = $this->dir->getDir('Stemcell_Catalog').'/data/operation-videos.xlsx';
$data = [];
$sheet = Excel::getExcelSheet($path);
foreach ($sheet->getRowIterator() as $row) {
if ($row->getRowIndex() == 1) {
continue;
}
$categoryName = $this->getCellValue($sheet, 'A'.$row->getRowIndex());
$categorySort = intval($this->getCellValue($sheet, 'B'.$row->getRowIndex()));
// $duration = $this->getCellValue($sheet, 'C'.$row->getRowIndex());
$duration = $sheet->getCell('C'.$row->getRowIndex())->getValue();
$videoTitle = $this->getCellValue($sheet, 'D'.$row->getRowIndex());
$videoId = $this->getCellValue($sheet, 'E'.$row->getRowIndex());
if (!empty($videoTitle)) {
$data[$categoryName]['label'] = $categoryName;
$data[$categoryName]['list'][] = ['name' => $videoTitle, 'duration' => $duration, 'video_id'=>$videoId];
}
}
return json_encode(array_values($data));
}
}
@@ -0,0 +1,99 @@
<?php
namespace Stemcell\Catalog\Model\Api;
use Magento\Framework\Webapi\Rest\Request as RestRequest;
use Stemcell\Catalog\Model\ResourceModel\Cryopreserve\CollectionFactory as CryopreserveCollectionFactory;
/**
* 样本冻存参考小工具接口
*/
class SampleCryopreserve
{
public function __construct(
private CryopreserveCollectionFactory $cryopreserveCollectionFactory,
private RestRequest $restRequest
) {
}
protected function getSamples() {
$samples = [];
$data = $this->cryopreserveCollectionFactory->create()->addFieldToSelect('sample')->load()->getData();
foreach ($data as $item) {
if (!isset($samples[$item['sample']])) {
$samples[$item['sample']] = ['sample' => $item['sample']];
}
}
return array_values($samples);
}
protected function getTypes()
{
$sample = trim((string)$this->restRequest->getParam("sample"));
$collection = $this->cryopreserveCollectionFactory->create();
if (!empty($sample)) {
$collection->addFieldToFilter('sample', $sample);
}
$data = [];
foreach ($collection->getItems() as $item) {
/* @var $item \Stemcell\Catalog\Model\Cryopreserve */
if (!isset($data[$item->getType()])) {
$data[$item->getType()] = ['type' => $item->getType()];
}
}
return array_values($data);
}
protected function getCellTypes()
{
$sample = trim((string)$this->restRequest->getParam("sample"));
$type = trim((string)$this->restRequest->getParam("type"));
$collection = $this->cryopreserveCollectionFactory->create();
if (!empty($type)) {
$collection->addFieldToFilter('sample', $sample)
->addFieldToFilter('type', $type);
}
$data = [];
foreach ($collection->getItems() as $item) {
/* @var $item \Stemcell\Catalog\Model\Cryopreserve */
if (!isset($data[$item->getCellType()])) {
$data[$item->getCellType()] = ['cellType' => $item->getCellType()];
}
}
return array_values($data);
}
/**
* @return array
*/
public function getFilters()
{
return ['samples'=>$this->getSamples(), 'types'=>$this->getTypes(), 'cellTypes'=>$this->getCellTypes()];
}
/**
* @return string
*/
public function execute() : string {
$sample = trim((string)$this->restRequest->getParam("sample"));
$type = trim((string)$this->restRequest->getParam("type"));
$cellType = trim((string)$this->restRequest->getParam("cellType"));
$collection = $this->cryopreserveCollectionFactory->create()
->addFieldToSelect(['reference_density', 'desc', 'reference']);
if (!empty($sample)) {
$collection->addFieldToFilter('sample', $sample);
}
if (!empty($type)) {
$collection->addFieldToFilter('type', $type);
}
if (!empty($cellType)) {
$collection->addFieldToFilter('cell_type', $cellType);
}
return json_encode(['filters' => $this->getFilters(), 'items' => $collection->getData()]);
}
}
@@ -0,0 +1,211 @@
<?php
namespace Stemcell\Catalog\Model\Api;
use Magento\Framework\Module\Dir;
use Magento\Framework\Webapi\Rest\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Magento\Framework\App\CacheInterface;
use Magento\Catalog\Helper\Image as ImageHelper;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
/**
* 小程序实用工具 - 多能干细胞维持培养工具
*/
class TesrProductFinder
{
protected array $filtersField = ['first', 'second', 'third', 'fourth'];
const CACHE_IDENTIFIER = 'tesr_product_finder_cache';
const IMAGE_PATH = 'catalog/product/cache/43f2e544b18f2e737c50422db3f53cf3/E/B/EB00005_8406f0a7325bcb2e1140145e13eef3cd_1_1.jpg';
const XML_PATH_WECHAT_TESR_PRODUCT_FINDER = 'commerce/wechat/tesr-product-finder';
public function __construct(
protected Dir $dir,
protected Request $restRequest,
protected CacheInterface $cache,
protected ImageHelper $imageHelper,
protected ProductRepositoryInterface $productRepository,
protected Product $product,
protected ProductCollectionFactory $productCollectionFactory,
protected ScopeConfigInterface $scopeConfig,
protected FilterProvider $filterProvider,
) {
}
// 保存数据到缓存
protected function saveToCache($data, $identifier, $tags = [], $lifeTime = null)
{
$tags = array_merge(['CUSTOM_TAG'], $tags);
$lifeTime = $lifeTime ?: 3600; // 默认1小时
$this->cache->save(
serialize($data),
$identifier,
$tags,
$lifeTime
);
}
// 从缓存加载数据
protected function loadFromCache($identifier)
{
$data = $this->cache->load($identifier);
return $data ? unserialize($data) : false;
}
/**
* @return array
*/
protected function getExcelData()
{
$data = $this->loadFromCache(self::CACHE_IDENTIFIER);
if ($data !== false) {
return $data;
}
$path = $this->dir->getDir('Stemcell_Catalog').'/data/tesr-product-finder.xlsx';
$spreadsheet = IOFactory::load($path);
$worksheet = $spreadsheet->getActiveSheet();
// 获取所有数据
$data = $worksheet->toArray();
// 第一行作为键名
$headers = array_shift($data);
// 转换为关联数组
$result = [];
foreach ($data as $row) {
$assocRow = [];
foreach ($headers as $index => $header) {
if ($header) {
$assocRow[$header] = $row[$index] ?? null;
if ($header=='skus') {
$skus = array_map('trim', explode(',', $assocRow[$header]));
$assocRow[$header] = $this->getProductsFromSku($skus);
}
}
}
$result[] = $assocRow;
}
$this->saveToCache($result, self::CACHE_IDENTIFIER);
return $result;
}
protected function getProductsFromSku(array $skus)
{
$productCollection = $this->productCollectionFactory->create()
->addAttributeToFilter('sku', ['in' => $skus])
->addAttributeToSelect(['small_image', 'name']);
$data = [];
foreach ($productCollection as $product) {
$data[] = ['sku' => $product->getSku(), 'name' => $product->getName(), 'image' => $this->getImageUrl($product)];
}
return $data;
}
protected function getImageUrl(Product $product): string
{
return $this->imageHelper
->init($product, 'category_page_list')
->setImageFile($product->getSmallImage())
->getUrl();
}
/**
* @param array $data
* @return array[]
*/
protected function getFilters(array $data) {
$filters = [];
foreach ($this->filtersField as $field) {
$filters[$field] = [];
}
foreach ($data as $row) {
foreach ($this->filtersField as $field) {
!in_array($row[$field], $filters[$field]) && $filters[$field][] = $row[$field];
}
}
return $filters;
}
protected function getBanners()
{
$config = $this->scopeConfig->getValue(
self::XML_PATH_WECHAT_TESR_PRODUCT_FINDER,
ScopeInterface::SCOPE_STORE
);
if (!$config) {
$config = [];
} else {
try {
$config = $this->filterProvider->getPageFilter()->filter($config);
$config = json_decode($config, true);
} catch (\Exception $e) {
$config = [];
}
}
$config = is_array($config) ? $config : [];
return $config['banners'] ?? '';
}
/**
* @return string
*/
public function execute()
{
$data = $this->getExcelData();
$result = [];
$criteria = $this->restRequest->getParams();
foreach ($criteria as $key => $value) {
$criteria[$key] = trim($value);
}
$isFilterComplete = true;
foreach ($this->filtersField as $field) {
if (empty($criteria[$field])) {
$isFilterComplete = false;
break;
}
}
if ($isFilterComplete) {
foreach ($data as $row) {
$notThisRow = false;
foreach ($this->filtersField as $field) {
if ($row[$field] != $criteria[$field]) {
$notThisRow = true;
break;
}
}
if ($notThisRow) {
continue;
} else {
$result = $row;
break;
}
}
}
$product = $this->productRepository->get('EB00005');
return json_encode([
'filters' => $this->getFilters($data),
'result' => $result,
'resources' => [
[
'id'=>2,
'name'=>'诱导多能干细胞:标准化且易获取的究模型',
'image_url' => $this->getImageUrl($product),
],
],
'banners' => $this->getBanners(),
]);
}
}