init
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\CertificationType;
|
||||
|
||||
use Esun\Catalog\Model\CertificationType;
|
||||
use Esun\Catalog\Model\CertificationTypeFactory;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class EditBlock extends Template
|
||||
{
|
||||
private ?CertificationType $type = null;
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly CertificationTypeFactory $typeFactory,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getTypeModel(): CertificationType
|
||||
{
|
||||
if ($this->type === null) {
|
||||
$this->type = $this->typeFactory->create();
|
||||
$id = (int)$this->getRequest()->getParam('id');
|
||||
if ($id) {
|
||||
$this->type->load($id);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
public function getSaveUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/certificationtype/save');
|
||||
}
|
||||
|
||||
public function getBackUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/certificationtype/index');
|
||||
}
|
||||
|
||||
public function getIconUrl(string $path): string
|
||||
{
|
||||
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\CertificationType;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\CertificationType\Collection;
|
||||
use Esun\Catalog\Model\ResourceModel\CertificationType\CollectionFactory;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class ListBlock extends Template
|
||||
{
|
||||
private ?Collection $types = null;
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly CollectionFactory $collectionFactory,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getTypes(): Collection
|
||||
{
|
||||
if ($this->types === null) {
|
||||
$this->types = $this->collectionFactory->create()
|
||||
->setOrder('sort_order', 'ASC')
|
||||
->setOrder('type_id', 'DESC');
|
||||
}
|
||||
|
||||
return $this->types;
|
||||
}
|
||||
|
||||
public function getNewUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/certificationtype/new');
|
||||
}
|
||||
|
||||
public function getEditUrl(int $id): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/certificationtype/edit', ['id' => $id]);
|
||||
}
|
||||
|
||||
public function getDeleteUrl(int $id): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/certificationtype/delete', ['id' => $id]);
|
||||
}
|
||||
|
||||
public function getIconUrl(string $path): string
|
||||
{
|
||||
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\ColorOption;
|
||||
|
||||
use Esun\Catalog\Model\ColorOption;
|
||||
use Esun\Catalog\Model\ColorOptionFactory;
|
||||
use Esun\Catalog\Model\Config\Source\ColorOptionOptions;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class EditBlock extends Template
|
||||
{
|
||||
private ?ColorOption $item = null;
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly ColorOptionFactory $colorOptionFactory,
|
||||
private readonly ColorOptionOptions $colorOptionOptions,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getItem(): ColorOption
|
||||
{
|
||||
if ($this->item === null) {
|
||||
$this->item = $this->colorOptionFactory->create();
|
||||
$id = (int)$this->getRequest()->getParam('id');
|
||||
if ($id) {
|
||||
$this->item->load($id);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->item;
|
||||
}
|
||||
|
||||
public function getColorOptions(): array
|
||||
{
|
||||
return $this->colorOptionOptions->toOptionArray();
|
||||
}
|
||||
|
||||
public function getSaveUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/coloroption/save');
|
||||
}
|
||||
|
||||
public function getBackUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/coloroption/index');
|
||||
}
|
||||
|
||||
public function getImageUrl(string $path): string
|
||||
{
|
||||
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\ColorOption;
|
||||
|
||||
use Esun\Catalog\Model\Config\Source\ColorOptionOptions;
|
||||
use Esun\Catalog\Model\ResourceModel\ColorOption\Collection;
|
||||
use Esun\Catalog\Model\ResourceModel\ColorOption\CollectionFactory;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class ListBlock extends Template
|
||||
{
|
||||
private ?Collection $items = null;
|
||||
private ?array $optionLabels = null;
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly CollectionFactory $collectionFactory,
|
||||
private readonly ColorOptionOptions $colorOptionOptions,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getItems(): Collection
|
||||
{
|
||||
if ($this->items === null) {
|
||||
$this->items = $this->collectionFactory->create()
|
||||
->setOrder('sort_order', 'ASC')
|
||||
->setOrder('entity_id', 'DESC');
|
||||
}
|
||||
|
||||
return $this->items;
|
||||
}
|
||||
|
||||
public function getColorOptionLabel(int $optionId): string
|
||||
{
|
||||
return $this->getOptionLabels()[$optionId] ?? (string)$optionId;
|
||||
}
|
||||
|
||||
public function getNewUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/coloroption/new');
|
||||
}
|
||||
|
||||
public function getEditUrl(int $id): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/coloroption/edit', ['id' => $id]);
|
||||
}
|
||||
|
||||
public function getDeleteUrl(int $id): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/coloroption/delete', ['id' => $id]);
|
||||
}
|
||||
|
||||
public function getImageUrl(string $path): string
|
||||
{
|
||||
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
|
||||
}
|
||||
|
||||
private function getOptionLabels(): array
|
||||
{
|
||||
if ($this->optionLabels === null) {
|
||||
$this->optionLabels = [];
|
||||
foreach ($this->colorOptionOptions->toOptionArray() as $option) {
|
||||
$this->optionLabels[(int)$option['value']] = (string)$option['label'];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->optionLabels;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\Faq;
|
||||
|
||||
use Esun\Catalog\Model\Faq;
|
||||
use Esun\Catalog\Model\FaqFactory;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
use Magento\Cms\Model\Wysiwyg\Config as WysiwygConfig;
|
||||
use Magento\Framework\Data\FormFactory;
|
||||
use Magento\Store\Model\System\Store;
|
||||
|
||||
class EditBlock extends Template
|
||||
{
|
||||
private ?Faq $faq = null;
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly FaqFactory $faqFactory,
|
||||
private readonly Store $storeSystem,
|
||||
private readonly FormFactory $formFactory,
|
||||
private readonly WysiwygConfig $wysiwygConfig,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getFaqModel(): Faq
|
||||
{
|
||||
if ($this->faq === null) {
|
||||
$this->faq = $this->faqFactory->create();
|
||||
$id = (int)$this->getRequest()->getParam('id');
|
||||
if ($id) {
|
||||
$this->faq->load($id);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->faq;
|
||||
}
|
||||
|
||||
public function getStoreOptions(): array
|
||||
{
|
||||
return $this->storeSystem->getStoreValuesForForm(false, true);
|
||||
}
|
||||
|
||||
public function getSaveUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/faq/save');
|
||||
}
|
||||
|
||||
public function getBackUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/faq/index');
|
||||
}
|
||||
|
||||
public function getContentEditorHtml(): string
|
||||
{
|
||||
$form = $this->formFactory->create();
|
||||
$editor = $form->addField('content', 'editor', [
|
||||
'name' => 'content',
|
||||
'label' => __('Content'),
|
||||
'title' => __('Content'),
|
||||
'style' => 'height:28em',
|
||||
'required' => false,
|
||||
'value' => (string)$this->getFaqModel()->getData('content'),
|
||||
'config' => $this->wysiwygConfig->getConfig([
|
||||
'add_variables' => false,
|
||||
'add_widgets' => true,
|
||||
'add_images' => true,
|
||||
'is_pagebuilder_enabled' => true,
|
||||
'pagebuilder_button' => true,
|
||||
]),
|
||||
]);
|
||||
|
||||
return $editor->getElementHtml();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\Faq;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\Faq\Collection;
|
||||
use Esun\Catalog\Model\ResourceModel\Faq\CollectionFactory;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
|
||||
class ListBlock extends Template
|
||||
{
|
||||
private ?Collection $faqs = null;
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly CollectionFactory $collectionFactory,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getFaqs(): Collection
|
||||
{
|
||||
if ($this->faqs === null) {
|
||||
$this->faqs = $this->collectionFactory->create()
|
||||
->setOrder('sort_order', 'ASC')
|
||||
->setOrder('faq_id', 'DESC');
|
||||
}
|
||||
|
||||
return $this->faqs;
|
||||
}
|
||||
|
||||
public function getNewUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/faq/new');
|
||||
}
|
||||
|
||||
public function getEditUrl(int $id): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/faq/edit', ['id' => $id]);
|
||||
}
|
||||
|
||||
public function getDeleteUrl(int $id): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/faq/delete', ['id' => $id]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\MixStepPricing;
|
||||
|
||||
use Esun\Catalog\Model\MixStepPricing\ValidationState;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
|
||||
class Form extends Template
|
||||
{
|
||||
protected $_template = 'Esun_Catalog::mix_step_pricing/form.phtml';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly ValidationState $validationState,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function isDelete(): bool
|
||||
{
|
||||
return $this->getMode() === 'delete';
|
||||
}
|
||||
|
||||
public function getMode(): string
|
||||
{
|
||||
return (string)$this->getData('mode');
|
||||
}
|
||||
|
||||
public function getValidationState(): array
|
||||
{
|
||||
return $this->validationState->get($this->getMode());
|
||||
}
|
||||
|
||||
public function getValidateUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/mixsteppricing/' . ($this->isDelete() ? 'validateDelete' : 'validateImport'));
|
||||
}
|
||||
|
||||
public function getRunUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/mixsteppricing/' . ($this->isDelete() ? 'runDelete' : 'runImport'));
|
||||
}
|
||||
|
||||
public function getTemplateUrl(): string
|
||||
{
|
||||
return $this->getUrl(
|
||||
'esun_catalog/mixsteppricing/' . ($this->isDelete() ? 'downloadDeleteTemplate' : 'downloadImportTemplate')
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\Product\Edit\Button;
|
||||
|
||||
use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Generic;
|
||||
use Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Framework\View\Element\UiComponent\Context;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Magento\UrlRewrite\Model\UrlFinderInterface;
|
||||
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
|
||||
|
||||
class Preview extends Generic
|
||||
{
|
||||
private StoreManagerInterface $storeManager;
|
||||
|
||||
private UrlFinderInterface $urlFinder;
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
Registry $registry,
|
||||
StoreManagerInterface $storeManager,
|
||||
UrlFinderInterface $urlFinder
|
||||
) {
|
||||
parent::__construct($context, $registry);
|
||||
$this->storeManager = $storeManager;
|
||||
$this->urlFinder = $urlFinder;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getButtonData(): array
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
|
||||
if (!$product || !$product->getId()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$url = json_encode(
|
||||
$this->getFrontendUrl((int) $product->getId(), (int) $product->getStoreId()),
|
||||
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
|
||||
);
|
||||
|
||||
return [
|
||||
'label' => __('Preview'),
|
||||
'class' => 'action-secondary',
|
||||
'on_click' => sprintf('window.open(%s, "_blank", "noopener");', $url),
|
||||
'sort_order' => 30,
|
||||
];
|
||||
}
|
||||
|
||||
private function getFrontendUrl(int $productId, int $storeId): string
|
||||
{
|
||||
$store = $storeId
|
||||
? $this->storeManager->getStore($storeId)
|
||||
: $this->storeManager->getDefaultStoreView();
|
||||
|
||||
$rewrites = $this->urlFinder->findAllByData([
|
||||
UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE,
|
||||
UrlRewrite::ENTITY_ID => $productId,
|
||||
UrlRewrite::STORE_ID => (int) $store->getId(),
|
||||
UrlRewrite::REDIRECT_TYPE => 0,
|
||||
]);
|
||||
|
||||
$requestPath = sprintf('catalog/product/view/id/%d/', $productId);
|
||||
foreach ($rewrites as $rewrite) {
|
||||
if (!$rewrite->getMetadata()) {
|
||||
$requestPath = $rewrite->getRequestPath();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return rtrim($store->getBaseUrl(UrlInterface::URL_TYPE_LINK), '/')
|
||||
. '/'
|
||||
. ltrim($requestPath, '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\ProductRecommendation;
|
||||
|
||||
use Esun\Catalog\Model\ProductRecommendation\ValidationState;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
|
||||
class ImportForm extends Template
|
||||
{
|
||||
protected $_template = 'Esun_Catalog::product_recommendation/import.phtml';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly ValidationState $validationState,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getValidationState(): array
|
||||
{
|
||||
return $this->validationState->get();
|
||||
}
|
||||
|
||||
public function getValidateUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/productrecommendation/validateImport');
|
||||
}
|
||||
|
||||
public function getRunUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/productrecommendation/runImport');
|
||||
}
|
||||
|
||||
public function getTemplateUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/productrecommendation/downloadTemplate');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\SpecificationBrand;
|
||||
|
||||
use Esun\Catalog\Model\SpecificationBrand;
|
||||
use Esun\Catalog\Model\SpecificationBrandFactory;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class EditBlock extends Template
|
||||
{
|
||||
private ?SpecificationBrand $brand = null;
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly SpecificationBrandFactory $brandFactory,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getBrand(): SpecificationBrand
|
||||
{
|
||||
if ($this->brand === null) {
|
||||
$this->brand = $this->brandFactory->create();
|
||||
$id = (int)$this->getRequest()->getParam('id');
|
||||
if ($id > 0) {
|
||||
$this->brand->load($id);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->brand;
|
||||
}
|
||||
|
||||
public function getSaveUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/specificationbrand/save');
|
||||
}
|
||||
|
||||
public function getBackUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/specificationbrand/index');
|
||||
}
|
||||
|
||||
public function getMediaUrl(string $path): string
|
||||
{
|
||||
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Adminhtml\SpecificationImport;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationBrand\CollectionFactory as BrandCollectionFactory;
|
||||
use Esun\Catalog\Model\SpecificationImport;
|
||||
use Esun\Catalog\Model\SpecificationImportFactory;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class EditBlock extends Template
|
||||
{
|
||||
private ?SpecificationImport $import = null;
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly SpecificationImportFactory $importFactory,
|
||||
private readonly BrandCollectionFactory $brandCollectionFactory,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getImport(): SpecificationImport
|
||||
{
|
||||
if ($this->import === null) {
|
||||
$this->import = $this->importFactory->create();
|
||||
$id = (int)$this->getRequest()->getParam('id');
|
||||
if ($id > 0) {
|
||||
$this->import->load($id);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->import;
|
||||
}
|
||||
|
||||
public function getBrands()
|
||||
{
|
||||
return $this->brandCollectionFactory->create()
|
||||
->addFieldToFilter('status', 1)
|
||||
->setOrder('sort_order', 'ASC')
|
||||
->setOrder('brand_name', 'ASC');
|
||||
}
|
||||
|
||||
public function getSaveUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/specificationimport/save');
|
||||
}
|
||||
|
||||
public function getBackUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/specificationimport/index');
|
||||
}
|
||||
|
||||
public function getBrandUrl(): string
|
||||
{
|
||||
return $this->getUrl('esun_catalog/specificationbrand/new');
|
||||
}
|
||||
|
||||
public function getMediaUrl(string $path): string
|
||||
{
|
||||
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Product;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\ColorOption\CollectionFactory as ColorOptionCollectionFactory;
|
||||
use Magento\Catalog\Block\Product\Context;
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
|
||||
use Magento\Eav\Model\Config as EavConfig;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Magento\Swatches\Helper\Data as SwatchHelper;
|
||||
use Magento\Swatches\Model\Swatch;
|
||||
|
||||
class AvailableColors extends Template
|
||||
{
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly Registry $registry,
|
||||
private readonly Json $json,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly Configurable $configurableType,
|
||||
private readonly EavConfig $eavConfig,
|
||||
private readonly ColorOptionCollectionFactory $colorOptionCollectionFactory,
|
||||
private readonly SwatchHelper $swatchHelper,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getProduct(): ?Product
|
||||
{
|
||||
$product = $this->registry->registry('current_product');
|
||||
return $product instanceof Product ? $product : null;
|
||||
}
|
||||
|
||||
public function getColorOptions(): array
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
if (!$product || $product->getTypeId() !== 'configurable') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$optionIds = [];
|
||||
foreach ($this->configurableType->getUsedProducts($product) as $child) {
|
||||
$optionId = (int)$child->getData('color');
|
||||
if ($optionId > 0 && !isset($optionIds[$optionId])) {
|
||||
$optionIds[$optionId] = count($optionIds);
|
||||
}
|
||||
}
|
||||
if (!$optionIds) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$labels = $this->getColorOptionLabels();
|
||||
$nativeSwatches = $this->swatchHelper->getSwatchesByOptionsId(array_keys($optionIds));
|
||||
$esunOptions = $this->getEsunOptions(array_keys($optionIds));
|
||||
$items = [];
|
||||
|
||||
foreach ($optionIds as $optionId => $orderIndex) {
|
||||
$esunOption = $esunOptions[$optionId] ?? null;
|
||||
if ($esunOption && !(bool)$esunOption->getData('status')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$label = $esunOption ? trim((string)$esunOption->getData('display_name')) : '';
|
||||
if ($label === '') {
|
||||
$label = $labels[$optionId] ?? (string)$optionId;
|
||||
}
|
||||
|
||||
$swatchColors = $esunOption
|
||||
? $this->normalizeSwatchColors((string)$esunOption->getData('swatch_colors'))
|
||||
: [];
|
||||
if (!$swatchColors) {
|
||||
$swatchColors = $this->getNativeSwatchColors($nativeSwatches[$optionId] ?? []);
|
||||
}
|
||||
|
||||
$ballImage = $esunOption ? (string)$esunOption->getData('ball_image') : '';
|
||||
$items[] = [
|
||||
'option_id' => $optionId,
|
||||
'label' => $label,
|
||||
'ball_image_url' => $ballImage !== '' ? $this->getMediaUrl($ballImage) : '',
|
||||
'swatch_colors' => $swatchColors,
|
||||
'colors' => $this->buildColorRows($label, $swatchColors),
|
||||
'sort_order' => $esunOption ? (int)$esunOption->getData('sort_order') : 0,
|
||||
'order_index' => $orderIndex,
|
||||
];
|
||||
}
|
||||
|
||||
usort($items, static function (array $a, array $b): int {
|
||||
$sort = ((int)$a['sort_order'] <=> (int)$b['sort_order']);
|
||||
return $sort !== 0 ? $sort : ((int)$a['order_index'] <=> (int)$b['order_index']);
|
||||
});
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
public function getColorSwatchConfigJson(array $colorOptions): string
|
||||
{
|
||||
$config = [];
|
||||
foreach ($colorOptions as $item) {
|
||||
if (!empty($item['swatch_colors'])) {
|
||||
$config[(string)$item['option_id']] = [
|
||||
'colors' => array_values($item['swatch_colors']),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->json->serialize(['options' => $config]);
|
||||
}
|
||||
|
||||
private function getEsunOptions(array $optionIds): array
|
||||
{
|
||||
$options = [];
|
||||
$collection = $this->colorOptionCollectionFactory->create()
|
||||
->addFieldToFilter('option_id', ['in' => $optionIds]);
|
||||
|
||||
foreach ($collection as $item) {
|
||||
$options[(int)$item->getData('option_id')] = $item;
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
private function getColorOptionLabels(): array
|
||||
{
|
||||
$labels = [];
|
||||
$attribute = $this->eavConfig->getAttribute('catalog_product', 'color');
|
||||
foreach ($attribute->getSource()->getAllOptions(false) as $option) {
|
||||
$optionId = (int)($option['value'] ?? 0);
|
||||
if ($optionId > 0) {
|
||||
$labels[$optionId] = (string)($option['label'] ?? '');
|
||||
}
|
||||
}
|
||||
|
||||
return $labels;
|
||||
}
|
||||
|
||||
private function getNativeSwatchColors(array $swatch): array
|
||||
{
|
||||
$type = (int)($swatch['type'] ?? Swatch::SWATCH_TYPE_EMPTY);
|
||||
$value = trim((string)($swatch['value'] ?? ''));
|
||||
if ($type !== Swatch::SWATCH_TYPE_VISUAL_COLOR || $value === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->normalizeSwatchColors($value);
|
||||
}
|
||||
|
||||
private function buildColorRows(string $label, array $swatchColors): array
|
||||
{
|
||||
$names = $this->splitColorNames($label, count($swatchColors));
|
||||
$rows = [];
|
||||
foreach (array_values($swatchColors) as $index => $color) {
|
||||
$rows[] = [
|
||||
'name' => $names[$index] ?? $label,
|
||||
'hex' => strtoupper((string)$color),
|
||||
];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
private function splitColorNames(string $label, int $count): array
|
||||
{
|
||||
if ($count <= 1) {
|
||||
return [$label];
|
||||
}
|
||||
|
||||
$names = array_values(array_filter(array_map('trim', preg_split('/\s*(?:,|\/|\+|&|-)\s*/', $label) ?: [])));
|
||||
if (count($names) === $count) {
|
||||
return $names;
|
||||
}
|
||||
|
||||
$spaceNames = array_values(array_filter(array_map('trim', preg_split('/\s+/', $label) ?: [])));
|
||||
return count($spaceNames) === $count ? $spaceNames : array_fill(0, $count, $label);
|
||||
}
|
||||
|
||||
private function normalizeSwatchColors(string $value): array
|
||||
{
|
||||
$parts = preg_split('/[\s,;]+/', trim($value)) ?: [];
|
||||
$colors = [];
|
||||
foreach ($parts as $part) {
|
||||
$color = trim($part);
|
||||
if ($color !== '' && preg_match('/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/', $color)) {
|
||||
$colors[] = strtoupper($color);
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($colors));
|
||||
}
|
||||
|
||||
private function getMediaUrl(string $path): string
|
||||
{
|
||||
if (preg_match('#^https?://#', $path)) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
return $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA)
|
||||
. ltrim($path, '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Product;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\ColorOption\CollectionFactory as ColorOptionCollectionFactory;
|
||||
use Esun\Catalog\Model\ResourceModel\Faq\CollectionFactory as FaqCollectionFactory;
|
||||
use Esun\Catalog\Model\ResourceModel\CertificationType\CollectionFactory as CertificationTypeCollectionFactory;
|
||||
use Esun\Catalog\Model\PrintingParameter;
|
||||
use Esun\Video\Model\ResourceModel\Video\CollectionFactory as VideoCollectionFactory;
|
||||
use Magento\Catalog\Api\ProductRepositoryInterface;
|
||||
use Magento\Catalog\Block\Product\Context;
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\Catalog\Model\Product\Gallery\ReadHandler as GalleryReadHandler;
|
||||
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
|
||||
use Magento\Eav\Model\Config as EavConfig;
|
||||
use Magento\Framework\Exception\NoSuchEntityException;
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
use Magento\Catalog\Helper\Output as CatalogOutputHelper;
|
||||
|
||||
class DetailContent extends Template
|
||||
{
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly Registry $registry,
|
||||
private readonly Json $json,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly Configurable $configurableType,
|
||||
private readonly EavConfig $eavConfig,
|
||||
private readonly ColorOptionCollectionFactory $colorOptionCollectionFactory,
|
||||
private readonly FaqCollectionFactory $faqCollectionFactory,
|
||||
private readonly CertificationTypeCollectionFactory $certificationTypeCollectionFactory,
|
||||
private readonly VideoCollectionFactory $videoCollectionFactory,
|
||||
private readonly GalleryReadHandler $galleryReadHandler,
|
||||
private readonly ResourceConnection $resourceConnection,
|
||||
private readonly ProductRepositoryInterface $productRepository,
|
||||
private readonly PrintingParameter $printingParameter,
|
||||
private readonly CatalogOutputHelper $catalogOutputHelper,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getProduct(): ?Product
|
||||
{
|
||||
$product = $this->registry->registry('current_product');
|
||||
return $product instanceof Product ? $product : null;
|
||||
}
|
||||
|
||||
public function getDescriptionHtml(): string
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
if (!$product) {
|
||||
return '';
|
||||
}
|
||||
return $this->catalogOutputHelper->productAttribute($product, (string)$product->getDescription(), 'description');
|
||||
//return $product ? (string)$product->getDescription() : '';
|
||||
}
|
||||
|
||||
public function getIndustryApplications(): array
|
||||
{
|
||||
return $this->normalizeItems($this->decodeProductJson('esun_industry_applications'));
|
||||
}
|
||||
|
||||
public function getCreativeVideos(): array
|
||||
{
|
||||
$items = $this->normalizeItems($this->decodeProductJson('esun_creative_video_ids'));
|
||||
$ids = [];
|
||||
foreach ($items as $item) {
|
||||
$id = (int)($item['video_id'] ?? 0);
|
||||
if ($id > 0) {
|
||||
$ids[$id] = $id;
|
||||
}
|
||||
}
|
||||
if (!$ids) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$videos = [];
|
||||
$mediaBaseUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
|
||||
$collection = $this->videoCollectionFactory->create()
|
||||
->addFieldToFilter('video_id', ['in' => array_values($ids)])
|
||||
->addFieldToFilter('status', 1);
|
||||
foreach ($collection as $video) {
|
||||
$videos[(int)$video->getId()] = [
|
||||
'id' => (int)$video->getId(),
|
||||
'cover_url' => $mediaBaseUrl . ltrim((string)$video->getData('cover_path'), '/'),
|
||||
'video_url' => $mediaBaseUrl . ltrim((string)$video->getData('video_path'), '/'),
|
||||
];
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($items as $item) {
|
||||
$id = (int)($item['video_id'] ?? 0);
|
||||
if (isset($videos[$id])) {
|
||||
$result[] = $videos[$id] + ['position' => (int)($item['position'] ?? 0)];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function getDetailGalleryImages(): array
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
if (!$product) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$items = $this->normalizeItems($this->decodeProductJson('esun_detail_gallery'));
|
||||
$uploadedImages = [];
|
||||
foreach ($items as $item) {
|
||||
$path = $this->extractImagePath($item['image'] ?? '');
|
||||
if ($path !== '') {
|
||||
$uploadedImages[] = [
|
||||
'url' => $this->getMediaUrl($path),
|
||||
'label' => (string)($item['label'] ?? ''),
|
||||
'value_id' => 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
if ($uploadedImages) {
|
||||
return $uploadedImages;
|
||||
}
|
||||
|
||||
if (!$items) {
|
||||
$items = $this->loadMappedGalleryItems((int)$product->getId());
|
||||
}
|
||||
if (!$items) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$this->galleryReadHandler->execute($product);
|
||||
$wantedValueIds = [];
|
||||
$wantedFiles = [];
|
||||
foreach ($items as $item) {
|
||||
if (!empty($item['value_id'])) {
|
||||
$wantedValueIds[(int)$item['value_id']] = true;
|
||||
}
|
||||
if (!empty($item['file'])) {
|
||||
$wantedFiles[(string)$item['file']] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$images = [];
|
||||
foreach ($product->getMediaGalleryImages() ?: [] as $image) {
|
||||
$valueId = (int)($image->getData('value_id') ?: $image->getData('id'));
|
||||
$file = (string)$image->getData('file');
|
||||
if (($valueId && isset($wantedValueIds[$valueId])) || ($file && isset($wantedFiles[$file]))) {
|
||||
$images[] = [
|
||||
'url' => (string)$image->getData('url'),
|
||||
'label' => (string)$image->getData('label'),
|
||||
'value_id' => $valueId,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $images;
|
||||
}
|
||||
|
||||
public function getFaqs(): array
|
||||
{
|
||||
$storeId = (int)$this->storeManager->getStore()->getId();
|
||||
$faqs = [];
|
||||
|
||||
$collection = $this->faqCollectionFactory->create()
|
||||
->addFieldToFilter('status', 1)
|
||||
->setOrder('sort_order', 'ASC')
|
||||
->setOrder('faq_id', 'ASC');
|
||||
foreach ($collection as $faq) {
|
||||
$storeIds = array_map('intval', explode(',', (string)$faq->getData('store_ids')));
|
||||
if (!in_array(0, $storeIds, true) && !in_array($storeId, $storeIds, true)) {
|
||||
continue;
|
||||
}
|
||||
$faqs[] = [
|
||||
'title' => (string)$faq->getData('title'),
|
||||
'content' => (string)$faq->getData('content'),
|
||||
'position' => (int)$faq->getData('sort_order'),
|
||||
];
|
||||
}
|
||||
|
||||
foreach ($this->normalizeItems($this->decodeProductJson('esun_product_faqs')) as $item) {
|
||||
if (!empty($item['title'])) {
|
||||
$faqs[] = [
|
||||
'title' => (string)$item['title'],
|
||||
'content' => (string)($item['content'] ?? ''),
|
||||
'position' => (int)($item['position'] ?? 0),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
usort($faqs, static fn(array $a, array $b): int => ($a['position'] <=> $b['position']));
|
||||
return $faqs;
|
||||
}
|
||||
|
||||
public function getPrintingParameters(): array
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
if (!$product) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->printingParameter->getByProductName((string)$product->getName());
|
||||
}
|
||||
|
||||
public function getPrintingParameterIconUrl(string $icon): string
|
||||
{
|
||||
$icon = trim($icon);
|
||||
if ($icon === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $this->getViewFileUrl('Esun_Catalog::images/printing-parameter/' . ltrim($icon, '/'));
|
||||
}
|
||||
|
||||
public function getCertificationDownloads(): array
|
||||
{
|
||||
$items = $this->normalizeItems($this->decodeProductJson('esun_certification_downloads'));
|
||||
if (!$items) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$typeIds = [];
|
||||
foreach ($items as $item) {
|
||||
$typeId = (int)($item['type_id'] ?? 0);
|
||||
if ($typeId > 0) {
|
||||
$typeIds[$typeId] = $typeId;
|
||||
}
|
||||
}
|
||||
if (!$typeIds) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$types = [];
|
||||
$collection = $this->certificationTypeCollectionFactory->create()
|
||||
->addFieldToFilter('type_id', ['in' => array_values($typeIds)])
|
||||
->addFieldToFilter('status', 1);
|
||||
foreach ($collection as $type) {
|
||||
$types[(int)$type->getId()] = [
|
||||
'name' => (string)$type->getData('name'),
|
||||
'icon' => (string)$type->getData('icon'),
|
||||
];
|
||||
}
|
||||
|
||||
$downloads = [];
|
||||
foreach ($items as $item) {
|
||||
$typeId = (int)($item['type_id'] ?? 0);
|
||||
$file = $this->extractFilePath($item['file'] ?? '');
|
||||
if ($typeId <= 0 || $file === '' || empty($types[$typeId])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$downloads[] = [
|
||||
'type_id' => $typeId,
|
||||
'name' => $types[$typeId]['name'],
|
||||
'icon_url' => $types[$typeId]['icon'] !== '' ? $this->getMediaUrl($types[$typeId]['icon']) : '',
|
||||
'file_url' => $this->getMediaUrl($file),
|
||||
'file_name' => basename($file),
|
||||
'position' => (int)($item['position'] ?? 0),
|
||||
];
|
||||
}
|
||||
|
||||
usort($downloads, static fn (array $a, array $b): int => ($a['position'] <=> $b['position']));
|
||||
return $downloads;
|
||||
}
|
||||
|
||||
public function getMediaUrl(string $path): string
|
||||
{
|
||||
if (preg_match('#^https?://#', $path)) {
|
||||
return $path;
|
||||
}
|
||||
return $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
|
||||
}
|
||||
|
||||
private function decodeProductJson(string $attributeCode): array
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
if (!$product) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$decoded = $this->decodeRows($product->getData($attributeCode));
|
||||
if ($decoded || (int)$product->getStoreId() === 0 || !(int)$product->getId()) {
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
try {
|
||||
$adminProduct = $this->productRepository->getById((int)$product->getId(), false, 0, true);
|
||||
return $this->decodeRows($adminProduct->getData($attributeCode));
|
||||
} catch (NoSuchEntityException) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private function decodeRows(mixed $value): array
|
||||
{
|
||||
if (is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$raw = trim((string)$value);
|
||||
if ($raw === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
$decoded = $this->json->unserialize($raw);
|
||||
return is_array($decoded) ? $decoded : [];
|
||||
} catch (\InvalidArgumentException) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private function normalizeItems(array $items): array
|
||||
{
|
||||
$items = array_filter($items, static function ($item): bool {
|
||||
if (!is_array($item)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !array_key_exists('enabled', $item) || filter_var($item['enabled'], FILTER_VALIDATE_BOOLEAN);
|
||||
});
|
||||
usort($items, static fn(array $a, array $b): int => ((int)($a['position'] ?? 0) <=> (int)($b['position'] ?? 0)));
|
||||
return array_values($items);
|
||||
}
|
||||
|
||||
private function extractImagePath(mixed $value): string
|
||||
{
|
||||
if (is_array($value)) {
|
||||
$image = reset($value);
|
||||
if (is_array($image)) {
|
||||
return (string)($image['file'] ?? $image['name'] ?? '');
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
return is_string($value) ? $value : '';
|
||||
}
|
||||
|
||||
private function extractFilePath(mixed $value): string
|
||||
{
|
||||
if (is_array($value)) {
|
||||
$file = reset($value);
|
||||
if (is_array($file)) {
|
||||
return (string)($file['file'] ?? $file['name'] ?? $file['url'] ?? '');
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
return is_string($value) ? $value : '';
|
||||
}
|
||||
|
||||
private function loadMappedGalleryItems(int $productId): array
|
||||
{
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$rows = $connection->fetchAll(
|
||||
$connection->select()
|
||||
->from($this->resourceConnection->getTableName('esun_catalog_product_gallery'))
|
||||
->where('product_id = ?', $productId)
|
||||
->where('section = ?', 'detail_gallery')
|
||||
->where('status = ?', 1)
|
||||
->order('sort_order ASC')
|
||||
);
|
||||
|
||||
return array_map(static fn(array $row): array => [
|
||||
'value_id' => (int)$row['value_id'],
|
||||
'position' => (int)$row['sort_order'],
|
||||
'enabled' => true,
|
||||
], $rows);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Product;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationBrand\CollectionFactory as BrandCollectionFactory;
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationFile\CollectionFactory as FileCollectionFactory;
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationImport\CollectionFactory as ImportCollectionFactory;
|
||||
use Esun\Catalog\Model\SpecificationMedia;
|
||||
use Esun\Catalog\Model\SpecificationZipImporter;
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class DownloadSpecifications extends Template
|
||||
{
|
||||
private ?array $items = null;
|
||||
private ?array $archives = null;
|
||||
private ?array $activeBrands = null;
|
||||
|
||||
public function __construct(
|
||||
Template\Context $context,
|
||||
private readonly Registry $registry,
|
||||
private readonly FileCollectionFactory $fileCollectionFactory,
|
||||
private readonly BrandCollectionFactory $brandCollectionFactory,
|
||||
private readonly ImportCollectionFactory $importCollectionFactory,
|
||||
private readonly SpecificationMedia $media,
|
||||
private readonly SpecificationZipImporter $zipImporter,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly Json $json,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getProduct(): ?Product
|
||||
{
|
||||
$product = $this->registry->registry('current_product');
|
||||
return $product instanceof Product ? $product : null;
|
||||
}
|
||||
|
||||
public function hasSpecifications(): bool
|
||||
{
|
||||
return (bool)($this->getItems() || $this->getArchives());
|
||||
}
|
||||
|
||||
public function getConfigJson(): string
|
||||
{
|
||||
$items = $this->getItems();
|
||||
$archives = $this->getArchives();
|
||||
$brands = [];
|
||||
$modelsByBrand = [];
|
||||
|
||||
foreach ($archives as $archive) {
|
||||
$brandId = (string)$archive['brand_id'];
|
||||
$brands[$brandId] = [
|
||||
'id' => $brandId,
|
||||
'name' => $archive['brand_name'],
|
||||
];
|
||||
}
|
||||
|
||||
foreach ($items as $item) {
|
||||
$brandId = (string)$item['brand_id'];
|
||||
$brands[$brandId] = [
|
||||
'id' => $brandId,
|
||||
'name' => $item['brand_name'],
|
||||
];
|
||||
$modelsByBrand[$brandId][$item['model_name']] = $item['model_name'];
|
||||
}
|
||||
|
||||
foreach ($modelsByBrand as $brandId => $models) {
|
||||
$modelsByBrand[$brandId] = array_values($models);
|
||||
sort($modelsByBrand[$brandId], SORT_NATURAL | SORT_FLAG_CASE);
|
||||
}
|
||||
|
||||
return $this->json->serialize([
|
||||
'items' => $items,
|
||||
'archives' => $archives,
|
||||
'brands' => array_values($brands),
|
||||
'modelsByBrand' => $modelsByBrand,
|
||||
]);
|
||||
}
|
||||
|
||||
private function getItems(): array
|
||||
{
|
||||
if ($this->items !== null) {
|
||||
return $this->items;
|
||||
}
|
||||
|
||||
$product = $this->getProduct();
|
||||
if (!$product) {
|
||||
return $this->items = [];
|
||||
}
|
||||
|
||||
$productName = strtolower(trim((string)$product->getName()));
|
||||
$mediaBaseUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
|
||||
$activeBrands = $this->getActiveBrands();
|
||||
if (!$activeBrands) {
|
||||
return $this->items = [];
|
||||
}
|
||||
|
||||
$items = [];
|
||||
$collection = $this->fileCollectionFactory->create()
|
||||
->addFieldToFilter('brand_id', ['in' => array_keys($activeBrands)])
|
||||
->setOrder('brand_name', 'ASC')
|
||||
->setOrder('model_name', 'ASC')
|
||||
->setOrder('file_name', 'ASC');
|
||||
$this->applyProductFileNameFilter($collection, $productName);
|
||||
|
||||
foreach ($collection as $file) {
|
||||
$filePath = (string)$file->getData('file_path');
|
||||
$logoPath = (string)$file->getData('brand_logo');
|
||||
$items[] = [
|
||||
'id' => (int)$file->getId(),
|
||||
'type' => 'file',
|
||||
'brand_id' => (int)$file->getData('brand_id'),
|
||||
'brand_name' => (string)$file->getData('brand_name'),
|
||||
'brand_logo_url' => $logoPath !== '' ? $mediaBaseUrl . ltrim($logoPath, '/') : '',
|
||||
'model_name' => (string)$file->getData('model_name'),
|
||||
'file_name' => strtoupper((string)$file->getData('file_name')),
|
||||
'file_url' => $mediaBaseUrl . ltrim($filePath, '/'),
|
||||
'file_size_label' => $this->formatFileSize((int)$file->getData('file_size')),
|
||||
'file_date' => $file->getData('file_mtime') ? date('Y-m-d', strtotime((string)$file->getData('file_mtime'))) : '',
|
||||
];
|
||||
}
|
||||
|
||||
return $this->items = $items;
|
||||
}
|
||||
|
||||
private function getArchives(): array
|
||||
{
|
||||
if ($this->archives !== null) {
|
||||
return $this->archives;
|
||||
}
|
||||
|
||||
$activeBrands = $this->getActiveBrands();
|
||||
if (!$activeBrands) {
|
||||
return $this->archives = [];
|
||||
}
|
||||
|
||||
$mediaBaseUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
|
||||
$archives = [];
|
||||
$seenBrandIds = [];
|
||||
$collection = $this->importCollectionFactory->create()
|
||||
->addFieldToFilter('status', 1)
|
||||
->addFieldToFilter('brand_id', ['in' => array_keys($activeBrands)])
|
||||
->setOrder('updated_at', 'DESC');
|
||||
|
||||
foreach ($collection as $import) {
|
||||
$brandId = (int)$import->getData('brand_id');
|
||||
$archivePath = (string)$import->getData('archive_file');
|
||||
if (isset($seenBrandIds[$brandId]) || $archivePath === '' || !$this->media->exists($archivePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$brand = $activeBrands[$brandId];
|
||||
$logoPath = (string)$brand['logo'];
|
||||
$archives[] = [
|
||||
'id' => 'archive-' . (int)$import->getId(),
|
||||
'type' => 'archive',
|
||||
'brand_id' => $brandId,
|
||||
'brand_name' => (string)$brand['name'],
|
||||
'brand_logo_url' => $logoPath !== '' ? $mediaBaseUrl . ltrim($logoPath, '/') : '',
|
||||
'model_name' => '',
|
||||
'file_name' => basename($archivePath),
|
||||
'file_url' => $mediaBaseUrl . ltrim($archivePath, '/'),
|
||||
'file_size_label' => $this->formatFileSize($this->media->getFileSize($archivePath)),
|
||||
'file_date' => $import->getData('updated_at')
|
||||
? date('Y-m-d', strtotime((string)$import->getData('updated_at')))
|
||||
: '',
|
||||
];
|
||||
$seenBrandIds[$brandId] = true;
|
||||
}
|
||||
|
||||
usort($archives, static fn (array $a, array $b): int => strcasecmp($a['brand_name'], $b['brand_name']));
|
||||
|
||||
return $this->archives = $archives;
|
||||
}
|
||||
|
||||
private function getActiveBrands(): array
|
||||
{
|
||||
if ($this->activeBrands !== null) {
|
||||
return $this->activeBrands;
|
||||
}
|
||||
|
||||
$brands = [];
|
||||
$collection = $this->brandCollectionFactory->create()
|
||||
->addFieldToFilter('status', 1)
|
||||
->setOrder('sort_order', 'ASC')
|
||||
->setOrder('brand_name', 'ASC');
|
||||
|
||||
foreach ($collection as $brand) {
|
||||
$brands[(int)$brand->getId()] = [
|
||||
'name' => (string)$brand->getData('brand_name'),
|
||||
'logo' => (string)$brand->getData('brand_logo'),
|
||||
];
|
||||
}
|
||||
|
||||
return $this->activeBrands = $brands;
|
||||
}
|
||||
|
||||
private function applyProductFileNameFilter($collection, string $productName): void
|
||||
{
|
||||
$connection = $collection->getConnection();
|
||||
if ($productName === '') {
|
||||
$collection->getSelect()->where('1 = 0');
|
||||
return;
|
||||
}
|
||||
|
||||
$collection->getSelect()->where(
|
||||
$connection->quoteInto(
|
||||
'LOWER(file_name) LIKE ?',
|
||||
'%' . addcslashes(strtolower($productName), '%_') . '%'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private function formatFileSize(int $bytes): string
|
||||
{
|
||||
if ($bytes >= 1048576) {
|
||||
return round($bytes / 1048576, 1) . ' MB';
|
||||
}
|
||||
|
||||
return round($bytes / 1024, 1) . ' KB';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Product;
|
||||
|
||||
use Esun\Catalog\Model\MixStepPriceProvider;
|
||||
use Magento\Catalog\Api\Data\ProductInterface;
|
||||
use Magento\Catalog\Helper\Image as ImageHelper;
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
|
||||
use Magento\Customer\Model\Group;
|
||||
use Magento\Customer\Model\Session as CustomerSession;
|
||||
use Magento\Framework\Locale\FormatInterface;
|
||||
use Magento\Framework\Pricing\PriceCurrencyInterface;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class PurchaseProgress extends Template
|
||||
{
|
||||
private ?array $configCache = null;
|
||||
|
||||
public function __construct(
|
||||
Template\Context $context,
|
||||
private readonly Registry $registry,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly CustomerSession $customerSession,
|
||||
private readonly FormatInterface $localeFormat,
|
||||
private readonly PriceCurrencyInterface $priceCurrency,
|
||||
private readonly Json $json,
|
||||
private readonly MixStepPriceProvider $mixStepPriceProvider,
|
||||
private readonly ImageHelper $imageHelper,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getProduct(): ?ProductInterface
|
||||
{
|
||||
$product = $this->registry->registry('current_product');
|
||||
|
||||
return $product instanceof ProductInterface ? $product : null;
|
||||
}
|
||||
|
||||
public function getJsonConfig(): string
|
||||
{
|
||||
return $this->json->serialize($this->getConfig());
|
||||
}
|
||||
|
||||
public function getConfig(): array
|
||||
{
|
||||
if ($this->configCache !== null) {
|
||||
return $this->configCache;
|
||||
}
|
||||
|
||||
$product = $this->getProduct();
|
||||
if (!$product instanceof Product) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$products = [];
|
||||
$defaultProductId = null;
|
||||
$sourceProducts = $this->getSourceProducts($product);
|
||||
|
||||
foreach ($sourceProducts as $sourceProduct) {
|
||||
$productConfig = $this->buildProductConfig($sourceProduct);
|
||||
if (!$productConfig) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$productId = (int)$sourceProduct->getId();
|
||||
$products[$productId] = $productConfig;
|
||||
$defaultProductId ??= $productId;
|
||||
}
|
||||
|
||||
if (!$products) {
|
||||
$products[(int)$product->getId()] = $this->buildProductConfig($product);
|
||||
$defaultProductId = (int)$product->getId();
|
||||
}
|
||||
|
||||
$mixRules = $product->getTypeId() === Configurable::TYPE_CODE
|
||||
? $this->mixStepPriceProvider->getRules($product, (int)$this->customerSession->getCustomerGroupId())
|
||||
: [];
|
||||
$mixItems = $mixRules ? $this->getMixItems($product, $sourceProducts) : [];
|
||||
|
||||
return $this->configCache = [
|
||||
'defaultProductId' => $defaultProductId,
|
||||
'products' => $products,
|
||||
'priceFormat' => $this->localeFormat->getPriceFormat(),
|
||||
'mixEnabled' => (bool)$mixItems,
|
||||
'mixAddUrl' => $this->getUrl('esun_cart/mix/add'),
|
||||
'mix' => [
|
||||
'parentId' => (int)$product->getId(),
|
||||
'tiers' => $this->prepareMixRulesForDisplay($mixRules),
|
||||
'items' => $mixItems,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function getInitialProductConfig(array $config): ?array
|
||||
{
|
||||
$defaultProductId = $config['defaultProductId'] ?? null;
|
||||
if (!$defaultProductId || empty($config['products'][$defaultProductId])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $config['products'][$defaultProductId];
|
||||
}
|
||||
|
||||
public function getInitialMilestones(array $productConfig): array
|
||||
{
|
||||
$milestones = [];
|
||||
|
||||
foreach ($productConfig['tiers'] ?? [] as $tier) {
|
||||
$qty = (int)($tier['qty'] ?? 0);
|
||||
$price = (float)($tier['price'] ?? 0);
|
||||
if ($qty <= 1 || $price <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$milestones[] = [
|
||||
'type' => 'tier',
|
||||
'qty' => $qty,
|
||||
'price' => $price,
|
||||
'percentage' => $tier['percentage'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
return $milestones;
|
||||
}
|
||||
|
||||
public function getInitialProgressPercent(array $milestones, int $qty = 1): float
|
||||
{
|
||||
$count = count($milestones);
|
||||
if ($count === 0) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
$firstQty = (int)($milestones[0]['qty'] ?? 1);
|
||||
$firstPosition = 50 / $count;
|
||||
if ($qty <= $firstQty) {
|
||||
return max(0.0, min($firstPosition, $qty / max(1, $firstQty) * $firstPosition));
|
||||
}
|
||||
|
||||
for ($index = 1; $index < $count; $index++) {
|
||||
$previousQty = (int)($milestones[$index - 1]['qty'] ?? 0);
|
||||
$currentQty = (int)($milestones[$index]['qty'] ?? 0);
|
||||
if ($qty > $currentQty) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$previousPosition = ($index - 0.5) / $count * 100;
|
||||
$currentPosition = ($index + 0.5) / $count * 100;
|
||||
$ratio = ($qty - $previousQty) / max(1, $currentQty - $previousQty);
|
||||
|
||||
return $previousPosition + $ratio * ($currentPosition - $previousPosition);
|
||||
}
|
||||
|
||||
$lastQty = (int)($milestones[$count - 1]['qty'] ?? 0);
|
||||
|
||||
return $qty === $lastQty ? ($count - 0.5) / $count * 100 : 100.0;
|
||||
}
|
||||
|
||||
public function formatAmount(float $amount): string
|
||||
{
|
||||
return $this->priceCurrency->format($amount, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Product[]
|
||||
*/
|
||||
private function getSourceProducts(Product $product): array
|
||||
{
|
||||
if ($product->getTypeId() !== Configurable::TYPE_CODE) {
|
||||
return [$product];
|
||||
}
|
||||
|
||||
$store = $this->storeManager->getStore();
|
||||
$collection = $product->getTypeInstance()->getUsedProductCollection($product);
|
||||
$collection->setStoreId((int)$store->getId());
|
||||
$collection->addStoreFilter($store);
|
||||
$attributesToSelect = [
|
||||
'name',
|
||||
'image',
|
||||
'small_image',
|
||||
'thumbnail',
|
||||
'price',
|
||||
'special_price',
|
||||
'special_from_date',
|
||||
'special_to_date',
|
||||
'tier_price',
|
||||
];
|
||||
foreach ($product->getTypeInstance()->getConfigurableAttributes($product) as $configurableAttribute) {
|
||||
$attributesToSelect[] = $configurableAttribute->getProductAttribute()->getAttributeCode();
|
||||
}
|
||||
$collection->addAttributeToSelect(array_unique($attributesToSelect));
|
||||
$collection->addAttributeToFilter('status', Product\Attribute\Source\Status::STATUS_ENABLED);
|
||||
|
||||
return iterator_to_array($collection);
|
||||
}
|
||||
|
||||
private function buildProductConfig(Product $sourceProduct): array
|
||||
{
|
||||
$oldPrice = (float)$sourceProduct->getPrice();
|
||||
$finalPrice = (float)$sourceProduct->getFinalPrice();
|
||||
|
||||
return [
|
||||
'finalPrice' => $finalPrice,
|
||||
'basePrice' => $oldPrice > 0 ? $oldPrice : $finalPrice,
|
||||
'tiers' => $this->getTierItems($sourceProduct),
|
||||
];
|
||||
}
|
||||
|
||||
private function getTierItems(Product $product): array
|
||||
{
|
||||
$customerGroupId = (int)$this->customerSession->getCustomerGroupId();
|
||||
$tierItems = [];
|
||||
|
||||
foreach ((array)$product->getTierPrice() as $tierPrice) {
|
||||
$allGroups = (int)($tierPrice['all_groups'] ?? 0) === 1;
|
||||
$tierCustomerGroupId = (int)($tierPrice['cust_group'] ?? Group::CUST_GROUP_ALL);
|
||||
|
||||
if (!$allGroups && $tierCustomerGroupId !== $customerGroupId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$qty = (int)ceil((float)($tierPrice['price_qty'] ?? 0));
|
||||
$price = (float)($tierPrice['website_price'] ?? $tierPrice['price'] ?? 0);
|
||||
if ($qty <= 0 || $price <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tierItems[$qty] = [
|
||||
'qty' => $qty,
|
||||
'price' => $price,
|
||||
'percentage' => array_key_exists('percentage_value', $tierPrice) && $tierPrice['percentage_value'] !== null
|
||||
? (float)$tierPrice['percentage_value']
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
ksort($tierItems);
|
||||
|
||||
return array_values($tierItems);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Product[] $sourceProducts
|
||||
*/
|
||||
private function getMixItems(Product $parentProduct, array $sourceProducts): array
|
||||
{
|
||||
$attributes = $parentProduct->getTypeInstance()->getConfigurableAttributes($parentProduct);
|
||||
$items = [];
|
||||
|
||||
foreach ($sourceProducts as $childProduct) {
|
||||
if (!$childProduct->isSaleable()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$childProduct->setCustomerGroupId((int)$this->customerSession->getCustomerGroupId());
|
||||
$basePrice = (float)$childProduct->getPriceModel()->getFinalPrice(1, $childProduct);
|
||||
$labels = [];
|
||||
$optionValues = [];
|
||||
foreach ($attributes as $configurableAttribute) {
|
||||
$attribute = $configurableAttribute->getProductAttribute();
|
||||
$optionValues[(string)$attribute->getId()] = (string)$childProduct->getData(
|
||||
$attribute->getAttributeCode()
|
||||
);
|
||||
$text = $childProduct->getAttributeText($attribute->getAttributeCode());
|
||||
if (is_array($text)) {
|
||||
$text = implode(', ', $text);
|
||||
}
|
||||
if ((string)$text !== '') {
|
||||
$labels[] = (string)$attribute->getStoreLabel() . ': ' . (string)$text;
|
||||
}
|
||||
}
|
||||
|
||||
$items[] = [
|
||||
'id' => (int)$childProduct->getId(),
|
||||
'sku' => (string)$childProduct->getSku(),
|
||||
'name' => $labels ? implode(' / ', $labels) : (string)$childProduct->getName(),
|
||||
'image' => $this->imageHelper->init($childProduct, 'product_page_image_small')->getUrl(),
|
||||
'basePrice' => $this->convertForDisplay($basePrice),
|
||||
'options' => $optionValues,
|
||||
];
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
private function prepareMixRulesForDisplay(array $rules): array
|
||||
{
|
||||
foreach ($rules as &$rule) {
|
||||
if (($rule['price_type'] ?? '') === 'fixed') {
|
||||
$rule['display_value'] = $this->convertForDisplay((float)$rule['value']);
|
||||
} else {
|
||||
$rule['display_value'] = (float)$rule['value'];
|
||||
}
|
||||
}
|
||||
unset($rule);
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
private function convertForDisplay(float $amount): float
|
||||
{
|
||||
return (float)$this->priceCurrency->convertAndRound($amount, $this->storeManager->getStore());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Product;
|
||||
|
||||
use Esun\Catalog\Model\ProductRecommendation\Resolver;
|
||||
use Magento\Catalog\Block\Product\AbstractProduct;
|
||||
use Magento\Catalog\Block\Product\Context;
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\Catalog\Model\Product\Attribute\Source\Status;
|
||||
use Magento\Catalog\Model\Product\Visibility as ProductVisibility;
|
||||
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
|
||||
use Magento\Catalog\Pricing\Price\FinalPrice;
|
||||
use Magento\Catalog\Pricing\Price\RegularPrice;
|
||||
use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableProductType;
|
||||
use Magento\Framework\Pricing\PriceCurrencyInterface;
|
||||
|
||||
class RecommendedProducts extends AbstractProduct
|
||||
{
|
||||
/** @var array<string, array{final: float, regular: float}> */
|
||||
private array $priceValues = [];
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly ProductVisibility $catalogProductVisibility,
|
||||
private readonly PriceCurrencyInterface $priceCurrency,
|
||||
private readonly Resolver $recommendationResolver,
|
||||
private readonly CollectionFactory $productCollectionFactory,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getRecommendedItems(): array
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
$websiteId = (int)$this->_storeManager->getStore()->getWebsiteId();
|
||||
$productIds = $this->recommendationResolver->resolveProductIds((int)$product->getId(), $websiteId);
|
||||
if (!$productIds) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$collection = $this->productCollectionFactory->create();
|
||||
$collection->setStoreId((int)$this->_storeManager->getStore()->getId());
|
||||
$collection->addAttributeToSelect(['name', 'small_image', 'thumbnail', 'price', 'special_price']);
|
||||
$collection->addIdFilter($productIds);
|
||||
$collection->addWebsiteFilter($websiteId);
|
||||
$collection->addAttributeToFilter('status', Status::STATUS_ENABLED);
|
||||
$collection->addAttributeToFilter('visibility', ['in' => $this->catalogProductVisibility->getVisibleInCatalogIds()]);
|
||||
|
||||
$itemsById = [];
|
||||
foreach ($collection as $item) {
|
||||
$itemsById[(int)$item->getId()] = $item;
|
||||
}
|
||||
$items = [];
|
||||
foreach ($productIds as $productId) {
|
||||
if (isset($itemsById[$productId])) {
|
||||
$items[] = $itemsById[$productId];
|
||||
}
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
public function getFormattedFinalPrice(Product $product): string
|
||||
{
|
||||
return $this->formatPrice($this->getFinalPriceValue($product));
|
||||
}
|
||||
|
||||
public function getFormattedRegularPrice(Product $product): string
|
||||
{
|
||||
return $this->formatPrice($this->getRegularPriceValue($product));
|
||||
}
|
||||
|
||||
public function hasOldPrice(Product $product): bool
|
||||
{
|
||||
return $this->getRegularPriceValue($product) > $this->getFinalPriceValue($product);
|
||||
}
|
||||
|
||||
public function getDiscountPercent(Product $product): ?int
|
||||
{
|
||||
$regularPrice = $this->getRegularPriceValue($product);
|
||||
$finalPrice = $this->getFinalPriceValue($product);
|
||||
if ($regularPrice <= 0.0 || $finalPrice >= $regularPrice) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int)round((($regularPrice - $finalPrice) / $regularPrice) * 100);
|
||||
}
|
||||
|
||||
private function getFinalPriceValue(Product $product): float
|
||||
{
|
||||
return $this->getPriceValues($product)['final'];
|
||||
}
|
||||
|
||||
private function getRegularPriceValue(Product $product): float
|
||||
{
|
||||
return $this->getPriceValues($product)['regular'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Configurable parents in this catalog have a zero base price. Magento's
|
||||
* standard resolver also returns zero when every associated option is out
|
||||
* of stock, so recommendation cards fall back to the lowest positive child
|
||||
* price while keeping the regular price from that same child.
|
||||
*
|
||||
* @return array{final: float, regular: float}
|
||||
*/
|
||||
private function getPriceValues(Product $product): array
|
||||
{
|
||||
$cacheKey = (int)$product->getStoreId() . ':' . (int)$product->getId();
|
||||
if (isset($this->priceValues[$cacheKey])) {
|
||||
return $this->priceValues[$cacheKey];
|
||||
}
|
||||
|
||||
$finalPrice = (float)$product->getPriceInfo()
|
||||
->getPrice(FinalPrice::PRICE_CODE)
|
||||
->getAmount()
|
||||
->getValue();
|
||||
$regularPrice = (float)$product->getPriceInfo()
|
||||
->getPrice(RegularPrice::PRICE_CODE)
|
||||
->getAmount()
|
||||
->getValue();
|
||||
|
||||
$typeInstance = $product->getTypeInstance();
|
||||
if ($finalPrice <= 0.0 && $typeInstance instanceof ConfigurableProductType) {
|
||||
foreach ($typeInstance->getUsedProducts($product) as $child) {
|
||||
$childFinalPrice = (float)$child->getPriceInfo()
|
||||
->getPrice(FinalPrice::PRICE_CODE)
|
||||
->getAmount()
|
||||
->getValue();
|
||||
if ($childFinalPrice <= 0.0 || ($finalPrice > 0.0 && $childFinalPrice >= $finalPrice)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$finalPrice = $childFinalPrice;
|
||||
$regularPrice = max(
|
||||
$childFinalPrice,
|
||||
(float)$child->getPriceInfo()
|
||||
->getPrice(RegularPrice::PRICE_CODE)
|
||||
->getAmount()
|
||||
->getValue()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->priceValues[$cacheKey] = [
|
||||
'final' => $finalPrice,
|
||||
'regular' => $regularPrice,
|
||||
];
|
||||
}
|
||||
|
||||
private function formatPrice(float $amount): string
|
||||
{
|
||||
return $this->priceCurrency->format($amount, false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Block\Product;
|
||||
|
||||
use Magento\Catalog\Api\Data\ProductInterface;
|
||||
use Magento\Catalog\Helper\Output as OutputHelper;
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class SpecialCampaign extends Template
|
||||
{
|
||||
public function __construct(
|
||||
Template\Context $context,
|
||||
private readonly Registry $registry,
|
||||
private readonly TimezoneInterface $timezone,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly OutputHelper $outputHelper,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getProduct(): ?ProductInterface
|
||||
{
|
||||
$product = $this->registry->registry('current_product');
|
||||
|
||||
return $product instanceof ProductInterface ? $product : null;
|
||||
}
|
||||
|
||||
public function getProductName(): string
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
|
||||
return $product ? (string)$product->getName() : '';
|
||||
}
|
||||
|
||||
public function getShortDescriptionHtml(): string
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
if (!$product instanceof Product) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$shortDescription = (string)$product->getShortDescription();
|
||||
if ($shortDescription === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
return (string)$this->outputHelper->productAttribute(
|
||||
$product,
|
||||
$shortDescription,
|
||||
'short_description'
|
||||
);
|
||||
}
|
||||
|
||||
public function getCampaignConfig(): array
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
if (!$product || $product->getTypeId() !== Configurable::TYPE_CODE) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$items = [];
|
||||
$nowTimestamp = $this->timezone->date()->getTimestamp();
|
||||
$store = $this->storeManager->getStore();
|
||||
$collection = $product->getTypeInstance()->getUsedProductCollection($product);
|
||||
$collection->setStoreId((int)$store->getId());
|
||||
$collection->addStoreFilter($store);
|
||||
$collection->addAttributeToSelect(['special_price', 'special_from_date', 'special_to_date']);
|
||||
$collection->addAttributeToFilter('status', Product\Attribute\Source\Status::STATUS_ENABLED);
|
||||
|
||||
foreach ($collection as $child) {
|
||||
$specialPrice = (float)$child->getData('special_price');
|
||||
$specialFromDate = (string)$child->getData('special_from_date');
|
||||
$specialToDate = (string)$child->getData('special_to_date');
|
||||
|
||||
if ($specialPrice <= 0 || $specialFromDate === '' || $specialToDate === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$toDate = $this->timezone->date(new \DateTime($specialToDate));
|
||||
$remainingMs = max(0, ($toDate->getTimestamp() - $nowTimestamp) * 1000);
|
||||
|
||||
$items[(int)$child->getId()] = [
|
||||
'remainingMs' => $remainingMs,
|
||||
];
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user