This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -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;
}
}
@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Console\Command;
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable as ConfigurableResource;
use Magento\Framework\Console\Cli;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Synchronizes configurable product categories to child products.
*/
class CopyConfigurableCategoriesCommand extends Command
{
private const COMMAND_NAME = 'esun:catalog:copy-configurable-categories';
/**
* @param CollectionFactory $productCollectionFactory Product collection factory.
* @param ProductResource $productResource Product resource.
* @param ConfigurableResource $configurableResource Configurable relation resource.
* @param CategoryLinkManagementInterface $categoryLinkManagement Category link service.
*/
public function __construct(
private readonly CollectionFactory $productCollectionFactory,
private readonly ProductResource $productResource,
private readonly ConfigurableResource $configurableResource,
private readonly CategoryLinkManagementInterface $categoryLinkManagement
) {
parent::__construct(self::COMMAND_NAME);
}
/**
* Configure the command.
*
* @return void
*/
protected function configure(): void
{
$this->setDescription(
'Synchronize configurable product categories to all child products.'
);
}
/**
* Run the category copy.
*
* @param InputInterface $input Console input.
* @param OutputInterface $output Console output.
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$parents = $this->productCollectionFactory->create();
$parents->addFieldToFilter('type_id', Configurable::TYPE_CODE);
$updated = 0;
$failed = 0;
/** @var Product $parent */
foreach ($parents as $parent) {
$categoryIds = array_values(array_unique(array_map(
'intval',
$this->productResource->getCategoryIds($parent)
)));
if ($categoryIds === []) {
continue;
}
$expectedCategoryIds = $categoryIds;
sort($expectedCategoryIds);
$childrenByGroup = $this->configurableResource->getChildrenIds((int) $parent->getId());
$childIds = [];
foreach ($childrenByGroup as $group) {
foreach ($group as $childId) {
$childIds[(int) $childId] = (int) $childId;
}
}
$childIds = array_values($childIds);
if ($childIds === []) {
continue;
}
$children = $this->productCollectionFactory->create();
$children->addIdFilter($childIds);
$children->addAttributeToSelect('sku');
/** @var Product $child */
foreach ($children as $child) {
$childCategoryIds = array_values(array_unique(array_map(
'intval',
$this->productResource->getCategoryIds($child)
)));
sort($childCategoryIds);
if ($childCategoryIds === $expectedCategoryIds) {
continue;
}
try {
$this->categoryLinkManagement->assignProductToCategories(
(string) $child->getSku(),
$categoryIds
);
$updated++;
$output->writeln(sprintf(
'<info>Updated %s from parent %s.</info>',
$child->getSku(),
$parent->getSku()
));
} catch (\Throwable $exception) {
$failed++;
$output->writeln(sprintf(
'<error>Failed %s: %s</error>',
$child->getSku(),
$exception->getMessage()
));
}
}
}
$output->writeln(sprintf(
'<comment>Finished: %d updated, %d failed.</comment>',
$updated,
$failed
));
return $failed === 0 ? Cli::RETURN_SUCCESS : Cli::RETURN_FAILURE;
}
}
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Console\Command;
use Esun\Catalog\Model\ResourceModel\SpecificationBrand\CollectionFactory as BrandCollectionFactory;
use Esun\Catalog\Model\SpecificationArchiveRebuilder;
use Magento\Framework\Console\Cli;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class RebuildSpecificationArchiveCommand extends Command
{
private const COMMAND_NAME = 'esun:catalog:specification-archive:rebuild';
private const OPTION_BRAND_ID = 'brand-id';
private const OPTION_FORCE = 'force';
public function __construct(
private readonly BrandCollectionFactory $brandCollectionFactory,
private readonly SpecificationArchiveRebuilder $archiveRebuilder
) {
parent::__construct(self::COMMAND_NAME);
}
protected function configure(): void
{
$this->setDescription('Rebuild downloadable specification ZIP archives from parsed specification files.');
$this->addOption(
self::OPTION_BRAND_ID,
null,
InputOption::VALUE_REQUIRED,
'Only rebuild the specified specification brand ID.'
);
$this->addOption(
self::OPTION_FORCE,
'f',
InputOption::VALUE_NONE,
'Overwrite an existing valid brand archive.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$brandIdOption = $input->getOption(self::OPTION_BRAND_ID);
$brandId = $brandIdOption !== null ? filter_var($brandIdOption, FILTER_VALIDATE_INT) : null;
if ($brandIdOption !== null && (!$brandId || $brandId < 1)) {
$output->writeln('<error>The --brand-id option must be a positive integer.</error>');
return Cli::RETURN_FAILURE;
}
$collection = $this->brandCollectionFactory->create()
->addFieldToFilter('status', 1)
->setOrder('sort_order', 'ASC')
->setOrder('brand_name', 'ASC');
if ($brandId !== null) {
$collection->addFieldToFilter('brand_id', $brandId);
}
if (!$collection->getSize()) {
$output->writeln('<error>No enabled specification brands matched the command options.</error>');
return Cli::RETURN_FAILURE;
}
$force = (bool)$input->getOption(self::OPTION_FORCE);
$failed = 0;
foreach ($collection as $brand) {
$brandName = (string)$brand->getData('brand_name');
try {
$result = $this->archiveRebuilder->rebuild($brand, $force);
if ($result['status'] === 'skipped') {
$output->writeln(sprintf('<comment>Skipped %s: archive already exists.</comment>', $brandName));
continue;
}
$message = sprintf(
'%s %s: %d file(s), %d missing file(s), %s',
ucfirst($result['status']),
$brandName,
$result['file_count'],
$result['missing_count'],
$result['path']
);
$output->writeln('<info>' . $message . '</info>');
} catch (\Throwable $exception) {
$failed++;
$output->writeln(sprintf('<error>Failed %s: %s</error>', $brandName, $exception->getMessage()));
}
}
return $failed === 0 ? Cli::RETURN_SUCCESS : Cli::RETURN_FAILURE;
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\CertificationType;
use Esun\Catalog\Model\CertificationTypeFactory;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Delete extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::certification_types_delete';
public function __construct(
Action\Context $context,
private readonly CertificationTypeFactory $typeFactory
) {
parent::__construct($context);
}
public function execute()
{
$redirect = $this->resultRedirectFactory->create();
try {
$type = $this->typeFactory->create()->load((int)$this->getRequest()->getParam('id'));
if (!$type->getId()) {
throw new LocalizedException(__('The certification type no longer exists.'));
}
$type->delete();
$this->messageManager->addSuccessMessage(__('The certification type has been deleted.'));
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
return $redirect->setPath('esun_catalog/certificationtype/index');
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\CertificationType;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Edit extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::certification_types';
public function __construct(
Action\Context $context,
private readonly PageFactory $resultPageFactory
) {
parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create();
$page->setActiveMenu('Esun_Catalog::certification_types');
$page->getConfig()->getTitle()->prepend(__('Edit Product Certification Type'));
return $page;
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\CertificationType;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::certification_types';
public function __construct(
Action\Context $context,
private readonly PageFactory $resultPageFactory
) {
parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create();
$page->setActiveMenu('Esun_Catalog::certification_types');
$page->getConfig()->getTitle()->prepend(__('Product Certification Type Management'));
return $page;
}
}
@@ -0,0 +1,8 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\CertificationType;
class NewAction extends Edit
{
}
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\CertificationType;
use Esun\Catalog\Model\CertificationTypeFactory;
use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
class Save extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::certification_types_save';
private const ICON_PATH = 'esun/catalog/certification-type';
public function __construct(
Action\Context $context,
private readonly CertificationTypeFactory $typeFactory,
private readonly UploaderFactory $uploaderFactory,
private readonly Filesystem $filesystem
) {
parent::__construct($context);
}
public function execute()
{
$id = (int)$this->getRequest()->getParam('type_id');
$redirect = $this->resultRedirectFactory->create();
try {
$type = $this->typeFactory->create();
if ($id) {
$type->load($id);
if (!$type->getId()) {
throw new LocalizedException(__('The certification type no longer exists.'));
}
}
$name = trim((string)$this->getRequest()->getParam('name'));
if ($name === '') {
throw new LocalizedException(__('Certification Type Name is required.'));
}
$icon = (string)$type->getData('icon');
$deleteIcon = (bool)$this->getRequest()->getParam('delete_icon');
if ($deleteIcon) {
$icon = '';
}
$uploadedIcon = $this->uploadIcon();
if ($uploadedIcon !== '') {
$icon = $uploadedIcon;
}
$type->addData([
'name' => $name,
'icon' => $icon,
'status' => $this->getRequest()->getParam('status') === '0' ? 0 : 1,
'sort_order' => (int)$this->getRequest()->getParam('sort_order'),
])->save();
$this->messageManager->addSuccessMessage(__('The certification type has been saved.'));
return $redirect->setPath('esun_catalog/certificationtype/index');
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
return $redirect->setPath($id ? 'esun_catalog/certificationtype/edit' : 'esun_catalog/certificationtype/new', $id ? ['id' => $id] : []);
}
}
private function uploadIcon(): string
{
$file = $_FILES['icon'] ?? null;
if (!is_array($file) || empty($file['name']) || (int)($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
return '';
}
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$mediaDirectory->create(self::ICON_PATH);
$uploader = $this->uploaderFactory->create(['fileId' => 'icon']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']);
$uploader->setAllowRenameFiles(true);
$result = $uploader->save($mediaDirectory->getAbsolutePath(self::ICON_PATH));
if (empty($result['file'])) {
return '';
}
return self::ICON_PATH . '/' . ltrim((string)$result['file'], '/');
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\ColorOption;
use Esun\Catalog\Model\ColorOptionFactory;
use Esun\Catalog\Model\ColorOption\CacheInvalidator;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Delete extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::color_options_delete';
public function __construct(
Action\Context $context,
private readonly ColorOptionFactory $colorOptionFactory,
private readonly CacheInvalidator $cacheInvalidator
) {
parent::__construct($context);
}
public function execute()
{
$redirect = $this->resultRedirectFactory->create();
try {
$item = $this->colorOptionFactory->create()->load((int)$this->getRequest()->getParam('id'));
if (!$item->getId()) {
throw new LocalizedException(__('The color option no longer exists.'));
}
$item->delete();
$this->cacheInvalidator->invalidate();
$this->messageManager->addSuccessMessage(__('The color option has been deleted.'));
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
return $redirect->setPath('esun_catalog/coloroption/index');
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\ColorOption;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Edit extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::color_options';
public function __construct(
Action\Context $context,
private readonly PageFactory $resultPageFactory
) {
parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create();
$page->setActiveMenu('Esun_Catalog::color_options');
$page->getConfig()->getTitle()->prepend(__('Edit Color Option'));
return $page;
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\ColorOption;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::color_options';
public function __construct(
Action\Context $context,
private readonly PageFactory $resultPageFactory
) {
parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create();
$page->setActiveMenu('Esun_Catalog::color_options');
$page->getConfig()->getTitle()->prepend(__('Color Option Management'));
return $page;
}
}
@@ -0,0 +1,8 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\ColorOption;
class NewAction extends Edit
{
}
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\ColorOption;
use Esun\Catalog\Model\ColorOptionFactory;
use Esun\Catalog\Model\ColorOptionImageUploader;
use Esun\Catalog\Model\ColorOption\CacheInvalidator;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Save extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::color_options_save';
public function __construct(
Action\Context $context,
private readonly ColorOptionFactory $colorOptionFactory,
private readonly ColorOptionImageUploader $imageUploader,
private readonly CacheInvalidator $cacheInvalidator
) {
parent::__construct($context);
}
public function execute()
{
$id = (int)$this->getRequest()->getParam('entity_id');
$redirect = $this->resultRedirectFactory->create();
try {
$item = $this->colorOptionFactory->create();
if ($id) {
$item->load($id);
if (!$item->getId()) {
throw new LocalizedException(__('The color option no longer exists.'));
}
}
$optionId = (int)$this->getRequest()->getParam('option_id');
if ($optionId <= 0) {
throw new LocalizedException(__('Color Option is required.'));
}
$ballImage = (string)$item->getData('ball_image');
if ((bool)$this->getRequest()->getParam('delete_ball_image')) {
$ballImage = '';
}
$uploadedImage = $this->imageUploader->upload('ball_image');
if ($uploadedImage !== '') {
$ballImage = $uploadedImage;
}
$item->addData([
'option_id' => $optionId,
'display_name' => trim((string)$this->getRequest()->getParam('display_name')),
'swatch_colors' => $this->normalizeSwatchColors((string)$this->getRequest()->getParam('swatch_colors')),
'ball_image' => $ballImage,
'is_hot_sale' => (int)$this->getRequest()->getParam('is_hot_sale') === 1 ? 1 : 0,
'status' => $this->getRequest()->getParam('status') === '0' ? 0 : 1,
'sort_order' => (int)$this->getRequest()->getParam('sort_order'),
])->save();
$this->cacheInvalidator->invalidate();
$this->messageManager->addSuccessMessage(__('The color option has been saved.'));
return $redirect->setPath('esun_catalog/coloroption/index');
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
return $redirect->setPath($id ? 'esun_catalog/coloroption/edit' : 'esun_catalog/coloroption/new', $id ? ['id' => $id] : []);
}
}
private function normalizeSwatchColors(string $value): string
{
$parts = preg_split('/[\s,;]+/', trim($value)) ?: [];
$colors = [];
foreach ($parts as $part) {
$color = trim($part);
if ($color === '') {
continue;
}
if (!str_starts_with($color, '#')) {
$color = '#' . $color;
}
if (!preg_match('/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/', $color)) {
throw new LocalizedException(__('Invalid swatch color "%1". Use hex values such as #FF0000.', $part));
}
$colors[] = strtoupper($color);
}
return implode(',', array_values(array_unique($colors)));
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\Faq;
use Esun\Catalog\Model\FaqFactory;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Delete extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::faqs_delete';
public function __construct(
Action\Context $context,
private readonly FaqFactory $faqFactory
) {
parent::__construct($context);
}
public function execute()
{
$redirect = $this->resultRedirectFactory->create();
try {
$faq = $this->faqFactory->create()->load((int)$this->getRequest()->getParam('id'));
if (!$faq->getId()) {
throw new LocalizedException(__('The FAQ no longer exists.'));
}
$faq->delete();
$this->messageManager->addSuccessMessage(__('The FAQ has been deleted.'));
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
return $redirect->setPath('esun_catalog/faq/index');
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\Faq;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Edit extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::faqs';
public function __construct(
Action\Context $context,
private readonly PageFactory $resultPageFactory
) {
parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create();
$page->setActiveMenu('Esun_Catalog::faqs');
$page->getConfig()->getTitle()->prepend(__('Edit Product FAQ'));
return $page;
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\Faq;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::faqs';
public function __construct(
Action\Context $context,
private readonly PageFactory $resultPageFactory
) {
parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create();
$page->setActiveMenu('Esun_Catalog::faqs');
$page->getConfig()->getTitle()->prepend(__('Product FAQ'));
return $page;
}
}
@@ -0,0 +1,8 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\Faq;
class NewAction extends Edit
{
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\Faq;
use Esun\Catalog\Model\FaqFactory;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Save extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::faqs_save';
public function __construct(
Action\Context $context,
private readonly FaqFactory $faqFactory
) {
parent::__construct($context);
}
public function execute()
{
$id = (int)$this->getRequest()->getParam('faq_id');
$redirect = $this->resultRedirectFactory->create();
try {
$faq = $this->faqFactory->create();
if ($id) {
$faq->load($id);
if (!$faq->getId()) {
throw new LocalizedException(__('The FAQ no longer exists.'));
}
}
$title = trim((string)$this->getRequest()->getParam('title'));
if ($title === '') {
throw new LocalizedException(__('Title is required.'));
}
$storeIds = (array)$this->getRequest()->getParam('store_ids', [0]);
$storeIds = array_map('intval', $storeIds);
if (!$storeIds) {
$storeIds = [0];
}
$faq->addData([
'title' => $title,
'content' => (string)$this->getRequest()->getParam('content'),
'store_ids' => implode(',', array_unique($storeIds)),
'status' => $this->getRequest()->getParam('status') === '0' ? 0 : 1,
'sort_order' => (int)$this->getRequest()->getParam('sort_order'),
])->save();
$this->messageManager->addSuccessMessage(__('The FAQ has been saved.'));
return $redirect->setPath('esun_catalog/faq/index');
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
return $redirect->setPath($id ? 'esun_catalog/faq/edit' : 'esun_catalog/faq/new', $id ? ['id' => $id] : []);
}
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\MixStepPricing;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Delete extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::mix_step_pricing_delete';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu(self::ADMIN_RESOURCE);
$page->getConfig()->getTitle()->prepend(__('Batch Delete Mix Step Pricing'));
return $page;
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\MixStepPricing;
use Esun\Catalog\Model\MixStepPricing\TemplateGenerator;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\RawFactory;
class DownloadDeleteTemplate extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::mix_step_pricing_delete';
public function __construct(
Action\Context $context,
private readonly TemplateGenerator $templateGenerator,
private readonly RawFactory $rawFactory
) {
parent::__construct($context);
}
public function execute()
{
return $this->rawFactory->create()
->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
->setHeader('Content-Disposition', 'attachment; filename="mix_step_pricing_delete.xlsx"')
->setContents($this->templateGenerator->createDelete());
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\MixStepPricing;
use Esun\Catalog\Model\MixStepPricing\TemplateGenerator;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\RawFactory;
class DownloadImportTemplate extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::mix_step_pricing_import';
public function __construct(
Action\Context $context,
private readonly TemplateGenerator $templateGenerator,
private readonly RawFactory $rawFactory
) {
parent::__construct($context);
}
public function execute()
{
return $this->rawFactory->create()
->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
->setHeader('Content-Disposition', 'attachment; filename="mix_step_pricing_import.xlsx"')
->setContents($this->templateGenerator->createImport());
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\MixStepPricing;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Import extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::mix_step_pricing_import';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu(self::ADMIN_RESOURCE);
$page->getConfig()->getTitle()->prepend(__('Batch Import Mix Step Pricing'));
return $page;
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\MixStepPricing;
use Esun\Catalog\Model\MixStepPricing\DeleteService;
use Esun\Catalog\Model\MixStepPricing\ValidationState;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem\DriverInterface;
class RunDelete extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::mix_step_pricing_delete';
public function __construct(
Action\Context $context,
private readonly DeleteService $deleteService,
private readonly ValidationState $validationState,
private readonly DriverInterface $filesystemDriver
) {
parent::__construct($context);
}
public function execute()
{
$state = $this->validationState->get('delete');
try {
if ((string)$this->getRequest()->getParam('confirm_delete') !== '1') {
throw new LocalizedException(__('Confirm that you understand this operation deletes all tiers.'));
}
$path = (string)($state['path'] ?? '');
if (empty($state['valid']) || $path === '' || !$this->filesystemDriver->isFile($path)) {
throw new LocalizedException(__('Validate an Excel file before running the delete.'));
}
$stats = $this->deleteService->run($path);
$this->validationState->clear('delete');
$this->filesystemDriver->deleteFile($path);
$this->messageManager->addSuccessMessage(__(
'Deleted Mix Step Pricing for %1 sku + website groups across %2 Store Views.',
$stats['groups'],
$stats['store_views']
));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
}
return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/delete');
}
}
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\MixStepPricing;
use Esun\Catalog\Model\MixStepPricing\ImportService;
use Esun\Catalog\Model\MixStepPricing\ValidationState;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem\DriverInterface;
class RunImport extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::mix_step_pricing_import';
public function __construct(
Action\Context $context,
private readonly ImportService $importService,
private readonly ValidationState $validationState,
private readonly DriverInterface $filesystemDriver
) {
parent::__construct($context);
}
public function execute()
{
$state = $this->validationState->get('import');
try {
$path = (string)($state['path'] ?? '');
if (empty($state['valid']) || $path === '' || !$this->filesystemDriver->isFile($path)) {
throw new LocalizedException(__('Validate an Excel file before running the import.'));
}
$stats = $this->importService->run($path);
$this->validationState->clear('import');
$this->filesystemDriver->deleteFile($path);
$this->messageManager->addSuccessMessage(__(
'Imported %1 sku + website groups across %2 Store Views.',
$stats['groups'],
$stats['store_views']
));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
}
return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/import');
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\MixStepPricing;
use Esun\Catalog\Model\MixStepPricing\DeleteService;
use Esun\Catalog\Model\MixStepPricing\FileUploader;
use Esun\Catalog\Model\MixStepPricing\ValidationState;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\ResultFactory;
class ValidateDelete extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::mix_step_pricing_delete';
public function __construct(
Action\Context $context,
private readonly FileUploader $fileUploader,
private readonly DeleteService $deleteService,
private readonly ValidationState $validationState
) {
parent::__construct($context);
}
public function execute()
{
$this->validationState->clear('delete');
try {
$path = $this->fileUploader->upload('excel_file');
$result = $this->deleteService->validate($path);
$this->validationState->save('delete', $path, $result);
if ($result['valid']) {
$this->messageManager->addSuccessMessage(__('Delete validation passed. Review the preview carefully.'));
}
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
}
return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/delete');
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\MixStepPricing;
use Esun\Catalog\Model\MixStepPricing\FileUploader;
use Esun\Catalog\Model\MixStepPricing\ImportService;
use Esun\Catalog\Model\MixStepPricing\ValidationState;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\ResultFactory;
class ValidateImport extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::mix_step_pricing_import';
public function __construct(
Action\Context $context,
private readonly FileUploader $fileUploader,
private readonly ImportService $importService,
private readonly ValidationState $validationState
) {
parent::__construct($context);
}
public function execute()
{
$this->validationState->clear('import');
try {
$path = $this->fileUploader->upload('excel_file');
$result = $this->importService->validate($path);
$this->validationState->save('import', $path, $result);
if ($result['valid']) {
$this->messageManager->addSuccessMessage(
__('Import validation passed. Review the preview before running the import.')
);
}
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
}
return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/import');
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\Product\Certification;
use Esun\Catalog\Model\CertificationFileUploader;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
class Upload extends Action implements HttpPostActionInterface
{
public const ADMIN_RESOURCE = 'Magento_Catalog::products';
public function __construct(
Action\Context $context,
private readonly CertificationFileUploader $fileUploader
) {
parent::__construct($context);
}
public function execute()
{
$fileId = (string)$this->getRequest()->getParam('param_name', 'file');
try {
$result = $this->fileUploader->saveFileToTmpDir($fileId);
} catch (\Exception $exception) {
$result = ['error' => $exception->getMessage(), 'errorcode' => $exception->getCode()];
}
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\Product\Image;
use Magento\Backend\App\Action;
use Magento\Catalog\Model\ImageUploader;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
class Upload extends Action implements HttpPostActionInterface
{
public const ADMIN_RESOURCE = 'Magento_Catalog::products';
public function __construct(
Action\Context $context,
private readonly ImageUploader $imageUploader
) {
parent::__construct($context);
}
public function execute()
{
$imageId = (string)$this->getRequest()->getParam('param_name', 'image');
try {
$result = $this->imageUploader->saveFileToTmpDir($imageId);
} catch (\Exception $exception) {
$result = ['error' => $exception->getMessage(), 'errorcode' => $exception->getCode()];
}
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\ProductRecommendation;
use Esun\Catalog\Model\ProductRecommendation\TemplateGenerator;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\RawFactory;
class DownloadTemplate extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::product_recommendation_import';
public function __construct(
Action\Context $context,
private readonly TemplateGenerator $templateGenerator,
private readonly RawFactory $rawFactory
) {
parent::__construct($context);
}
public function execute()
{
return $this->rawFactory->create()
->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
->setHeader('Content-Disposition', 'attachment; filename="product_recommendations.xlsx"')
->setContents($this->templateGenerator->create());
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\ProductRecommendation;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Import extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::product_recommendation_import';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu(self::ADMIN_RESOURCE);
$page->getConfig()->getTitle()->prepend(__('Import Product Recommendations'));
return $page;
}
}
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\ProductRecommendation;
use Esun\Catalog\Model\ProductRecommendation\ImportService;
use Esun\Catalog\Model\ProductRecommendation\ValidationState;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem\DriverInterface;
class RunImport extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::product_recommendation_import';
public function __construct(
Action\Context $context,
private readonly ImportService $importService,
private readonly ValidationState $validationState,
private readonly DriverInterface $filesystemDriver
) {
parent::__construct($context);
}
public function execute()
{
$state = $this->validationState->get();
try {
$path = (string)($state['path'] ?? '');
if (empty($state['valid']) || $path === '' || !$this->filesystemDriver->isFile($path)) {
throw new LocalizedException(__('Validate an Excel file before running the import.'));
}
$stats = $this->importService->run($path);
$this->validationState->clear();
$this->filesystemDriver->deleteFile($path);
$this->messageManager->addSuccessMessage(__(
'Replaced %1 product + website recommendation sets with %2 recommendations.',
$stats['groups'],
$stats['recommendations']
));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
}
return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/import');
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\ProductRecommendation;
use Esun\Catalog\Model\ProductRecommendation\FileUploader;
use Esun\Catalog\Model\ProductRecommendation\ImportService;
use Esun\Catalog\Model\ProductRecommendation\ValidationState;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\ResultFactory;
class ValidateImport extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::product_recommendation_import';
public function __construct(
Action\Context $context,
private readonly FileUploader $fileUploader,
private readonly ImportService $importService,
private readonly ValidationState $validationState
) {
parent::__construct($context);
}
public function execute()
{
$this->validationState->clear();
try {
$path = $this->fileUploader->upload('excel_file');
$result = $this->importService->validate($path);
$this->validationState->save($path, $result);
if ($result['valid']) {
$this->messageManager->addSuccessMessage(
__('Validation passed. Review the complete replacement preview before importing.')
);
} else {
foreach (array_slice((array)$result['errors'], 0, 20) as $error) {
$this->messageManager->addErrorMessage($error);
}
}
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
}
return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/import');
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\SpecificationBrand;
use Esun\Catalog\Model\SpecificationBrandFactory;
use Esun\Catalog\Model\SpecificationMedia;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Delete extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::specification_brands_delete';
public function __construct(
Action\Context $context,
private readonly SpecificationBrandFactory $brandFactory,
private readonly SpecificationMedia $media
) {
parent::__construct($context);
}
public function execute()
{
try {
$brand = $this->brandFactory->create()->load((int)$this->getRequest()->getParam('id'));
if (!$brand->getId()) {
throw new LocalizedException(__('The brand no longer exists.'));
}
$logo = (string)$brand->getData('brand_logo');
$brandId = (int)$brand->getId();
$brand->delete();
$this->media->delete($logo);
$this->media->deleteBrandFiles($brandId);
$this->messageManager->addSuccessMessage(__('The brand has been deleted.'));
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
return $this->resultRedirectFactory->create()->setPath('esun_catalog/specificationbrand/index');
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\SpecificationBrand;
use Esun\Catalog\Model\SpecificationBrandFactory;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Edit extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::specification_brands_save';
public function __construct(
Action\Context $context,
private readonly PageFactory $pageFactory,
private readonly SpecificationBrandFactory $brandFactory
) {
parent::__construct($context);
}
public function execute()
{
$id = (int)$this->getRequest()->getParam('id');
if ($id > 0 && !$this->brandFactory->create()->load($id)->getId()) {
$this->messageManager->addErrorMessage(__('The brand no longer exists.'));
return $this->resultRedirectFactory->create()->setPath('esun_catalog/specificationbrand/index');
}
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_Catalog::specification_brands');
$page->getConfig()->getTitle()->prepend($id ? __('Edit Specification Brand') : __('New Specification Brand'));
return $page;
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\SpecificationBrand;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::specification_brands';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_Catalog::specification_brands');
$page->getConfig()->getTitle()->prepend(__('Download Specification Brands'));
return $page;
}
}
@@ -0,0 +1,8 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\SpecificationBrand;
class NewAction extends Edit
{
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\SpecificationBrand;
use Esun\Catalog\Model\SpecificationBrandFactory;
use Esun\Catalog\Model\SpecificationMedia;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Save extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::specification_brands_save';
public function __construct(
Action\Context $context,
private readonly SpecificationBrandFactory $brandFactory,
private readonly SpecificationMedia $media
) {
parent::__construct($context);
}
public function execute()
{
$id = (int)$this->getRequest()->getParam('brand_id');
$redirect = $this->resultRedirectFactory->create();
try {
$brand = $this->brandFactory->create();
if ($id > 0) {
$brand->load($id);
if (!$brand->getId()) {
throw new LocalizedException(__('The brand no longer exists.'));
}
}
$brandName = trim((string)$this->getRequest()->getParam('brand_name'));
if ($brandName === '') {
throw new LocalizedException(__('Brand Name is required.'));
}
$oldLogo = (string)$brand->getData('brand_logo');
$logo = $oldLogo;
if ($this->getRequest()->getParam('delete_logo')) {
$logo = '';
}
$newLogo = $this->media->saveLogo('brand_logo');
if ($newLogo !== null) {
$logo = $newLogo;
}
$brand->addData([
'brand_name' => $brandName,
'brand_logo' => $logo,
'is_product_specific' => $this->getRequest()->getParam('is_product_specific') === '0' ? 0 : 1,
'status' => $this->getRequest()->getParam('status') === '0' ? 0 : 1,
'sort_order' => (int)$this->getRequest()->getParam('sort_order'),
])->save();
if ($oldLogo !== '' && $oldLogo !== $logo) {
$this->media->delete($oldLogo);
}
$this->messageManager->addSuccessMessage(__('The brand has been saved.'));
return $redirect->setPath('esun_catalog/specificationbrand/index');
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
return $redirect->setPath(
$id ? 'esun_catalog/specificationbrand/edit' : 'esun_catalog/specificationbrand/new',
$id ? ['id' => $id] : []
);
}
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\SpecificationImport;
use Esun\Catalog\Model\SpecificationImportFactory;
use Esun\Catalog\Model\SpecificationMedia;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Delete extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::specification_imports_delete';
public function __construct(
Action\Context $context,
private readonly SpecificationImportFactory $importFactory,
private readonly SpecificationMedia $media
) {
parent::__construct($context);
}
public function execute()
{
try {
$import = $this->importFactory->create()->load((int)$this->getRequest()->getParam('id'));
if (!$import->getId()) {
throw new LocalizedException(__('The import no longer exists.'));
}
$brandId = (int)$import->getData('brand_id');
$archive = (string)$import->getData('archive_file');
$import->delete();
$this->media->delete($archive);
$this->media->deleteBrandParsedFiles($brandId);
$this->messageManager->addSuccessMessage(__('The import has been deleted.'));
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
return $this->resultRedirectFactory->create()->setPath('esun_catalog/specificationimport/index');
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\SpecificationImport;
use Esun\Catalog\Model\SpecificationImportFactory;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Edit extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::specification_imports_save';
public function __construct(
Action\Context $context,
private readonly PageFactory $pageFactory,
private readonly SpecificationImportFactory $importFactory
) {
parent::__construct($context);
}
public function execute()
{
$id = (int)$this->getRequest()->getParam('id');
if ($id > 0 && !$this->importFactory->create()->load($id)->getId()) {
$this->messageManager->addErrorMessage(__('The import no longer exists.'));
return $this->resultRedirectFactory->create()->setPath('esun_catalog/specificationimport/index');
}
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_Catalog::specification_imports');
$page->getConfig()->getTitle()->prepend($id ? __('Edit Specifications ZIP') : __('Upload Specifications ZIP'));
return $page;
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\SpecificationImport;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::specification_imports';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute()
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_Catalog::specification_imports');
$page->getConfig()->getTitle()->prepend(__('Specifications Management'));
return $page;
}
}
@@ -0,0 +1,8 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\SpecificationImport;
class NewAction extends Edit
{
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Adminhtml\SpecificationImport;
use Esun\Catalog\Model\SpecificationBrandFactory;
use Esun\Catalog\Model\SpecificationImportFactory;
use Esun\Catalog\Model\SpecificationMedia;
use Esun\Catalog\Model\SpecificationZipImporter;
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
class Save extends Action
{
public const ADMIN_RESOURCE = 'Esun_Catalog::specification_imports_save';
public function __construct(
Action\Context $context,
private readonly SpecificationBrandFactory $brandFactory,
private readonly SpecificationImportFactory $importFactory,
private readonly SpecificationMedia $media,
private readonly SpecificationZipImporter $zipImporter
) {
parent::__construct($context);
}
public function execute()
{
$id = (int)$this->getRequest()->getParam('import_id');
$redirect = $this->resultRedirectFactory->create();
try {
$brandId = (int)$this->getRequest()->getParam('brand_id');
$brand = $this->brandFactory->create()->load($brandId);
if (!$brand->getId()) {
throw new LocalizedException(__('Please select a valid brand.'));
}
$archivePath = null;
if ($this->media->hasUpload('archive_file')) {
$this->media->deleteBrandArchiveFiles($brandId);
$archivePath = $this->media->saveArchive('archive_file', $brandId);
}
if ($archivePath === null) {
if ($id <= 0) {
throw new LocalizedException(__('Please upload a ZIP file.'));
}
$import = $this->importFactory->create()->load($id);
$archivePath = (string)$import->getData('archive_file');
}
$import = $this->zipImporter->import($brand, $archivePath);
$this->messageManager->addSuccessMessage(
__('The ZIP file has been imported. %1 file(s) were parsed.', (int)$import->getData('file_count'))
);
return $redirect->setPath('esun_catalog/specificationimport/index');
} catch (\Throwable $e) {
$this->messageManager->addErrorMessage($e->getMessage());
return $redirect->setPath(
$id ? 'esun_catalog/specificationimport/edit' : 'esun_catalog/specificationimport/new',
$id ? ['id' => $id] : []
);
}
}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Controller\Status;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\App\ResourceConnection;
use Magento\Wishlist\Model\WishlistFactory;
class Index extends Action implements HttpGetActionInterface
{
public function __construct(
Context $context,
private readonly RequestInterface $request,
private readonly JsonFactory $jsonFactory,
private readonly Session $customerSession,
private readonly WishlistFactory $wishlistFactory,
private readonly ResourceConnection $resourceConnection
) {
parent::__construct($context);
}
public function execute(): Json
{
$result = $this->jsonFactory->create();
$customerId = (int)$this->customerSession->getCustomerId();
$productId = (int)$this->request->getParam('product_id');
if (!$customerId || !$productId) {
return $result->setData(['active' => false]);
}
$wishlist = $this->wishlistFactory->create()->loadByCustomerId($customerId, false);
if (!$wishlist->getId()) {
return $result->setData(['active' => false]);
}
$connection = $this->resourceConnection->getConnection();
$active = $connection->fetchOne(
$connection->select()
->from(
$this->resourceConnection->getTableName('wishlist_item'),
['wishlist_item_id']
)
->where('wishlist_id = ?', (int)$wishlist->getId())
->where('product_id = ?', $productId)
->limit(1)
) !== false;
return $result->setData(['active' => $active]);
}
}
@@ -0,0 +1,133 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Framework\UrlInterface;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Store\Model\StoreManagerInterface;
class CertificationFileUploader
{
private const BASE_TMP_PATH = 'tmp/esun/catalog/certification';
private const BASE_PATH = 'esun/catalog/certification';
private const PRODUCT_BASE_PATH = self::BASE_PATH . '/product';
private const ALLOWED_EXTENSIONS = ['pdf', 'doc', 'docx', 'zip', 'rar', '7z'];
public function __construct(
private readonly UploaderFactory $uploaderFactory,
private readonly Filesystem $filesystem,
private readonly StoreManagerInterface $storeManager
) {
}
public function saveFileToTmpDir(string $fileId): array
{
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$mediaDirectory->create(self::BASE_TMP_PATH);
$uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
$uploader->setAllowedExtensions(self::ALLOWED_EXTENSIONS);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$result = $uploader->save($mediaDirectory->getAbsolutePath(self::BASE_TMP_PATH));
if (!$result || empty($result['file'])) {
throw new LocalizedException(__('The certification file could not be uploaded.'));
}
$file = ltrim((string)$result['file'], '/');
$relativePath = self::BASE_TMP_PATH . '/' . $file;
$result['file'] = $relativePath;
$result['name'] = (string)($result['name'] ?? basename($file));
$result['url'] = $this->getMediaUrl($relativePath);
return $result;
}
public function moveFileFromTmp(string $file, string $sku = ''): string
{
$file = $this->normalizePath($file);
if ($file === '') {
return '';
}
if (str_starts_with($file, self::BASE_PATH . '/')) {
return $file;
}
$basename = basename($file);
$tmpPath = str_starts_with($file, self::BASE_TMP_PATH . '/')
? $file
: self::BASE_TMP_PATH . '/' . $basename;
$targetDirectory = $this->getTargetDirectory($sku);
$targetPath = $targetDirectory . '/' . $basename;
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
if (!$mediaDirectory->isExist($tmpPath)) {
return $file;
}
$mediaDirectory->create($targetDirectory);
if ($mediaDirectory->isExist($targetPath)) {
$targetPath = $targetDirectory . '/' . $this->getUniqueFilename($targetDirectory, $basename);
}
$mediaDirectory->renameFile($tmpPath, $targetPath);
return $targetPath;
}
public function getAllowedExtensions(): array
{
return self::ALLOWED_EXTENSIONS;
}
private function normalizePath(string $value): string
{
$path = parse_url($value, PHP_URL_PATH) ?: $value;
$marker = '/media/';
$position = strpos($path, $marker);
if ($position !== false) {
$path = substr($path, $position + strlen($marker));
}
return ltrim($path, '/');
}
private function getTargetDirectory(string $sku): string
{
$sku = trim($sku);
if ($sku === '') {
return self::BASE_PATH;
}
$safeSku = preg_replace('/[^A-Za-z0-9._-]+/', '_', $sku) ?: '';
$safeSku = trim($safeSku, '._-');
return $safeSku !== '' ? self::PRODUCT_BASE_PATH . '/' . $safeSku : self::BASE_PATH;
}
private function getUniqueFilename(string $targetDirectory, string $basename): string
{
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$info = pathinfo($basename);
$filename = $info['filename'] ?? 'certification';
$extension = isset($info['extension']) ? '.' . $info['extension'] : '';
$candidate = $basename;
$index = 1;
while ($mediaDirectory->isExist($targetDirectory . '/' . $candidate)) {
$candidate = $filename . '_' . $index . $extension;
$index++;
}
return $candidate;
}
private function getMediaUrl(string $path): string
{
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . ltrim($path, '/');
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model;
use Magento\Framework\Model\AbstractModel;
class CertificationType extends AbstractModel
{
protected function _construct(): void
{
$this->_init(ResourceModel\CertificationType::class);
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model;
use Magento\Framework\Model\AbstractModel;
class ColorOption extends AbstractModel
{
protected function _construct(): void
{
$this->_init(ResourceModel\ColorOption::class);
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ColorOption;
use Magento\Framework\App\Cache\TypeListInterface;
class CacheInvalidator
{
private const CACHE_TYPES = ['block_html', 'full_page'];
public function __construct(
private readonly TypeListInterface $cacheTypeList
) {
}
public function invalidate(): void
{
foreach (self::CACHE_TYPES as $cacheType) {
$this->cacheTypeList->cleanType($cacheType);
}
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ColorOption;
use Magento\Framework\App\ResourceConnection;
class HotSaleOptionProvider
{
private ?array $optionIds = null;
public function __construct(
private readonly ResourceConnection $resourceConnection
) {
}
public function getOptionIds(): array
{
if ($this->optionIds !== null) {
return $this->optionIds;
}
$connection = $this->resourceConnection->getConnection();
$select = $connection->select()
->from(
$this->resourceConnection->getTableName('esun_catalog_color_option'),
['option_id']
)
->where('status = ?', 1)
->where('is_hot_sale = ?', 1);
$this->optionIds = array_map('intval', $connection->fetchCol($select));
return $this->optionIds;
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
class ColorOptionImageUploader
{
private const BASE_PATH = 'esun/catalog/color-option';
public function __construct(
private readonly UploaderFactory $uploaderFactory,
private readonly Filesystem $filesystem
) {
}
public function upload(string $fileId): string
{
$file = $_FILES[$fileId] ?? null;
if (!is_array($file) || empty($file['name']) || (int)($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
return '';
}
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$mediaDirectory->create(self::BASE_PATH);
$uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif', 'webp']);
$uploader->setAllowRenameFiles(true);
$result = $uploader->save($mediaDirectory->getAbsolutePath(self::BASE_PATH));
return !empty($result['file'])
? self::BASE_PATH . '/' . ltrim((string)$result['file'], '/')
: '';
}
public function saveBase64Image(string $dataUrl, string $fileName): string
{
if ($dataUrl === '') {
return '';
}
if (!preg_match('#^data:image/(png|jpe?g|gif|webp);base64,(.+)$#i', $dataUrl, $matches)) {
throw new LocalizedException(__('The color ball image format is invalid.'));
}
$extension = strtolower($matches[1]);
if ($extension === 'jpeg') {
$extension = 'jpg';
}
$contents = base64_decode($matches[2], true);
if ($contents === false) {
throw new LocalizedException(__('The color ball image could not be decoded.'));
}
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$mediaDirectory->create(self::BASE_PATH);
$baseName = pathinfo($fileName, PATHINFO_FILENAME) ?: 'color-ball';
$baseName = preg_replace('/[^A-Za-z0-9._-]+/', '_', $baseName) ?: 'color-ball';
$baseName = trim($baseName, '._-') ?: 'color-ball';
$candidate = $baseName . '.' . $extension;
$index = 1;
while ($mediaDirectory->isExist(self::BASE_PATH . '/' . $candidate)) {
$candidate = $baseName . '_' . $index . '.' . $extension;
$index++;
}
$path = self::BASE_PATH . '/' . $candidate;
$mediaDirectory->writeFile($path, $contents);
return $path;
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\Config\Backend;
use Esun\Catalog\Model\PrintingParameter\ExcelParser;
use Magento\Config\Model\Config\Backend\File;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Framework\Module\Dir\Reader as ModuleDirReader;
use Magento\Framework\Serialize\Serializer\Json;
class PrintingParameterExcel extends File
{
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
\Magento\Config\Model\Config\Backend\File\RequestData\RequestDataInterface $requestData,
Filesystem $filesystem,
private readonly ExcelParser $excelParser,
private readonly Json $json,
private readonly ModuleDirReader $moduleDirReader,
?\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
?\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct(
$context,
$registry,
$config,
$cacheTypeList,
$uploaderFactory,
$requestData,
$filesystem,
$resource,
$resourceCollection,
$data
);
}
public function beforeSave()
{
$file = $this->getFileData();
parent::beforeSave();
if (!$file || !(string)$this->getValue()) {
return $this;
}
$sourcePath = $this->_mediaDirectory->getAbsolutePath('esun/catalog/printing_parameter/' . ltrim((string)$this->getValue(), '/'));
$data = $this->excelParser->parse($sourcePath);
$this->writeJson($data);
return $this;
}
protected function _getAllowedExtensions(): array
{
return ['xlsx'];
}
private function writeJson(array $data): void
{
$moduleDir = $this->moduleDirReader->getModuleDir('', 'Esun_Catalog');
$dataDir = $moduleDir . '/data';
if (!is_dir($dataDir) && !mkdir($dataDir, 0775, true) && !is_dir($dataDir)) {
throw new LocalizedException(__('Unable to create the Esun Catalog data directory.'));
}
$json = $this->json->serialize($data);
$path = $dataDir . '/printing-parameters.json';
if (file_put_contents($path, json_encode(json_decode($json, true), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) === false) {
throw new LocalizedException(__('Unable to write the printing parameter JSON file.'));
}
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\Config\Source;
use Esun\Catalog\Model\ResourceModel\CertificationType\CollectionFactory;
use Magento\Framework\Data\OptionSourceInterface;
class CertificationTypeOptions implements OptionSourceInterface
{
public function __construct(
private readonly CollectionFactory $collectionFactory
) {
}
public function toOptionArray(): array
{
$options = [['value' => '', 'label' => __('Select a certification type')]];
$collection = $this->collectionFactory->create()
->addFieldToFilter('status', 1)
->setOrder('sort_order', 'ASC')
->setOrder('name', 'ASC');
foreach ($collection as $type) {
$options[] = [
'value' => (string)$type->getId(),
'label' => (string)$type->getData('name'),
];
}
return $options;
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\Config\Source;
use Magento\Eav\Model\Config as EavConfig;
use Magento\Framework\Data\OptionSourceInterface;
class ColorOptionOptions implements OptionSourceInterface
{
public function __construct(
private readonly EavConfig $eavConfig
) {
}
public function toOptionArray(): array
{
$attribute = $this->eavConfig->getAttribute('catalog_product', 'color');
$options = [];
foreach ($attribute->getSource()->getAllOptions(false) as $option) {
$value = (int)($option['value'] ?? 0);
if ($value <= 0) {
continue;
}
$options[] = [
'value' => $value,
'label' => (string)($option['label'] ?? ''),
];
}
return $options;
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\Config\Source;
use Magento\Customer\Model\Group;
use Magento\Customer\Model\ResourceModel\Group\CollectionFactory;
use Magento\Framework\Data\OptionSourceInterface;
class MixCustomerGroupOptions implements OptionSourceInterface
{
public function __construct(private readonly CollectionFactory $collectionFactory)
{
}
public function toOptionArray(): array
{
$options = [
['value' => Group::CUST_GROUP_ALL, 'label' => __('ALL GROUPS')],
];
$collection = $this->collectionFactory->create()->setOrder('customer_group_code', 'ASC');
foreach ($collection as $group) {
$options[] = [
'value' => (int)$group->getId(),
'label' => (string)$group->getCode(),
];
}
return $options;
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
class MixPriceTypeOptions implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 'percent', 'label' => __('Discount Percentage')],
['value' => 'fixed', 'label' => __('Fixed Unit Price')],
];
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\Config\Source;
use Esun\Video\Model\ResourceModel\Video\CollectionFactory;
use Magento\Framework\Data\OptionSourceInterface;
class VideoOptions implements OptionSourceInterface
{
public function __construct(
private readonly CollectionFactory $collectionFactory
) {
}
public function toOptionArray(): array
{
$options = [['value' => '', 'label' => __('Select a video')]];
foreach ($this->collectionFactory->create()->addFieldToFilter('status', 1)->setOrder('video_id', 'DESC') as $video) {
$options[] = [
'value' => (string)$video->getId(),
'label' => sprintf('#%d - %s', (int)$video->getId(), (string)$video->getData('title')),
];
}
return $options;
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model;
use Magento\Framework\Model\AbstractModel;
class Faq extends AbstractModel
{
protected function _construct(): void
{
$this->_init(ResourceModel\Faq::class);
}
}
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model;
use Esun\Catalog\Setup\Patch\Data\AddMixStepPricesAttribute;
use Magento\Catalog\Model\Product;
use Magento\Customer\Model\Group;
use Magento\Framework\Serialize\Serializer\Json;
class MixStepPriceProvider
{
public function __construct(private readonly Json $json)
{
}
public function getRules(Product $parentProduct, int $customerGroupId): array
{
$rows = $parentProduct->getData(AddMixStepPricesAttribute::ATTRIBUTE_CODE);
if (is_string($rows) && trim($rows) !== '') {
try {
$rows = $this->json->unserialize($rows);
} catch (\InvalidArgumentException) {
$rows = [];
}
}
if (!is_array($rows)) {
return [];
}
$rules = [];
foreach ($rows as $row) {
if (!is_array($row) || (isset($row['enabled']) && !(bool)$row['enabled'])) {
continue;
}
$ruleGroupId = (int)($row['customer_group_id'] ?? Group::CUST_GROUP_ALL);
if ($ruleGroupId !== Group::CUST_GROUP_ALL && $ruleGroupId !== $customerGroupId) {
continue;
}
$quantity = (int)($row['qty'] ?? 0);
$value = (float)($row['value'] ?? 0);
$priceType = (string)($row['price_type'] ?? 'percent');
if ($quantity < 2 || $value <= 0 || !in_array($priceType, ['percent', 'fixed'], true)) {
continue;
}
$specificity = $ruleGroupId === $customerGroupId ? 1 : 0;
if (isset($rules[$quantity]) && $rules[$quantity]['specificity'] > $specificity) {
continue;
}
$rules[$quantity] = [
'qty' => $quantity,
'price_type' => $priceType,
'value' => $value,
'specificity' => $specificity,
];
}
ksort($rules);
return array_map(static function (array $rule): array {
unset($rule['specificity']);
return $rule;
}, array_values($rules));
}
public function getActiveRule(array $rules, float $quantity): ?array
{
$activeRule = null;
foreach ($rules as $rule) {
if ($quantity >= (float)$rule['qty']) {
$activeRule = $rule;
}
}
return $activeRule;
}
public function calculateUnitPrice(float $basePrice, ?array $rule): float
{
if (!$rule) {
return max(0, $basePrice);
}
if (($rule['price_type'] ?? '') === 'fixed') {
return max(0, min($basePrice, (float)$rule['value']));
}
return max(0, $basePrice * (1 - ((float)$rule['value'] / 100)));
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\MixStepPricing;
use Esun\Catalog\Setup\Patch\Data\AddMixStepPricesAttribute;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Action;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Serialize\Serializer\Json;
class AttributeWriter
{
public function __construct(
private readonly Action $productAction,
private readonly ResourceConnection $resourceConnection,
private readonly Json $json,
private readonly CacheInterface $cache
) {
}
public function write(array $groups, bool $delete): array
{
$connection = $this->resourceConnection->getConnection();
$writtenGroups = 0;
$writtenStoreViews = 0;
$connection->beginTransaction();
try {
foreach ($groups as $group) {
$value = $this->json->serialize($delete ? [] : $group['rules']);
foreach ($group['store_ids'] as $storeId) {
$this->productAction->updateAttributes(
[(int)$group['product_id']],
[AddMixStepPricesAttribute::ATTRIBUTE_CODE => $value],
(int)$storeId
);
$writtenStoreViews++;
}
$writtenGroups++;
}
$connection->commit();
$productIds = array_unique(array_map(
static fn(array $group): int => (int)$group['product_id'],
$groups
));
$this->cache->clean(array_map(
static fn(int $productId): string => Product::CACHE_TAG . '_' . $productId,
$productIds
));
} catch (\Throwable $exception) {
$connection->rollBack();
throw $exception;
}
return ['groups' => $writtenGroups, 'store_views' => $writtenStoreViews];
}
}
@@ -0,0 +1,239 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\MixStepPricing;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
class BatchValidator
{
public function __construct(
private readonly ProductRepositoryInterface $productRepository,
private readonly WebsiteResolver $websiteResolver,
private readonly RuleNormalizer $ruleNormalizer
) {
}
public function validateImport(array $rows): array
{
$errors = [];
$groups = [];
$products = [];
$validRows = [];
$invalidRows = [];
foreach ($rows as $row) {
$rowNumber = (int)($row['row'] ?? 0);
$sku = trim((string)($row['sku'] ?? ''));
$websiteAlias = trim((string)($row['website'] ?? ''));
if ($sku === '') {
$reason = 'sku is required.';
$errors[] = $this->rowError($rowNumber, $reason);
$invalidRows[] = $this->invalidImportRow($row, $reason);
continue;
}
try {
$website = $this->websiteResolver->resolve($websiteAlias);
$product = $products[$sku] ??= $this->productRepository->get($sku, false, 0);
if ($product->getTypeId() !== Configurable::TYPE_CODE) {
throw new LocalizedException(__('SKU "%1" is not a configurable product.', $sku));
}
$rule = $this->ruleNormalizer->fromSpreadsheetRow($row);
} catch (NoSuchEntityException) {
$reason = sprintf('SKU "%s" does not exist.', $sku);
$errors[] = $this->rowError($rowNumber, $reason);
$invalidRows[] = $this->invalidImportRow($row, $reason);
continue;
} catch (LocalizedException $exception) {
$reason = $exception->getMessage();
$errors[] = $this->rowError($rowNumber, $reason);
$invalidRows[] = $this->invalidImportRow($row, $reason);
continue;
}
$key = $sku . '|' . $websiteAlias;
if (!isset($groups[$key])) {
$groups[$key] = [
'sku' => $sku,
'website' => $websiteAlias,
'product_id' => (int)$product->getId(),
'store_ids' => $website['store_ids'],
'rules' => [],
'row_numbers' => [],
];
}
$quantity = (int)$rule['qty'];
if (isset($groups[$key]['rules'][$quantity])) {
$reason = sprintf(
'Combined Qty From %d is duplicated for %s + %s.',
$quantity,
$sku,
$websiteAlias
);
$errors[] = $this->rowError($rowNumber, $reason);
$invalidRows[] = $this->invalidImportRow($row, $reason);
continue;
}
$groups[$key]['rules'][$quantity] = $rule;
$groups[$key]['row_numbers'][] = $rowNumber;
$validRows[] = [
'row' => $rowNumber,
'sku' => $sku,
'website' => $websiteAlias,
'combined_qty_from' => $quantity,
'pricing_method' => $rule['price_type'] === RuleNormalizer::PRICE_TYPE_PERCENT
? 'Discount Percentage'
: 'Unit Price',
'value' => $rule['value'],
];
}
foreach ($groups as &$group) {
ksort($group['rules']);
$group['rules'] = array_values($group['rules']);
}
unset($group);
return $this->result($rows, $groups, $errors, [], $validRows, $invalidRows);
}
public function validateDelete(array $rows): array
{
$errors = [];
$warnings = [];
$groups = [];
$products = [];
$validRows = [];
$invalidRows = [];
foreach ($rows as $row) {
$rowNumber = (int)($row['row'] ?? 0);
$sku = trim((string)($row['sku'] ?? ''));
$websiteAlias = trim((string)($row['website'] ?? ''));
if ($sku === '') {
$reason = 'sku is required.';
$errors[] = $this->rowError($rowNumber, $reason);
$invalidRows[] = $this->invalidDeleteRow($row, $reason);
continue;
}
try {
$website = $this->websiteResolver->resolve($websiteAlias);
} catch (LocalizedException $exception) {
$reason = $exception->getMessage();
$errors[] = $this->rowError($rowNumber, $reason);
$invalidRows[] = $this->invalidDeleteRow($row, $reason);
continue;
}
$key = $sku . '|' . $websiteAlias;
if (isset($groups[$key])) {
$reason = sprintf('%s + %s is duplicated.', $sku, $websiteAlias);
$errors[] = $this->rowError($rowNumber, $reason);
$invalidRows[] = $this->invalidDeleteRow($row, $reason);
continue;
}
try {
$product = $products[$sku] ??= $this->productRepository->get($sku, false, 0);
} catch (NoSuchEntityException) {
$reason = sprintf('SKU "%s" does not exist and will be skipped.', $sku);
$warnings[] = $this->rowError($rowNumber, $reason);
$invalidRows[] = $this->invalidDeleteRow($row, $reason);
continue;
}
if ($product->getTypeId() !== Configurable::TYPE_CODE) {
$reason = sprintf('SKU "%s" is not a configurable product.', $sku);
$errors[] = $this->rowError($rowNumber, $reason);
$invalidRows[] = $this->invalidDeleteRow($row, $reason);
continue;
}
$groups[$key] = [
'sku' => $sku,
'website' => $websiteAlias,
'product_id' => (int)$product->getId(),
'store_ids' => $website['store_ids'],
'rules' => [],
'row_numbers' => [$rowNumber],
];
$validRows[] = [
'row' => $rowNumber,
'sku' => $sku,
'website' => $websiteAlias,
];
}
if ($errors === [] && $groups === []) {
$errors[] = 'No existing configurable products were found to delete.';
}
return $this->result($rows, $groups, $errors, $warnings, $validRows, $invalidRows);
}
private function result(
array $rows,
array $groups,
array $errors,
array $warnings,
array $validRows,
array $invalidRows
): array
{
$storeViewWrites = array_sum(array_map(
static fn(array $group): int => count($group['store_ids']),
$groups
));
return [
'valid' => $errors === [],
'errors' => $errors,
'warnings' => $warnings,
'groups' => array_values($groups),
'valid_rows' => $validRows,
'invalid_rows' => $invalidRows,
'stats' => [
'rows' => count($rows),
'valid_rows' => count($validRows),
'invalid_rows' => count($invalidRows),
'groups' => count($groups),
'store_view_writes' => $storeViewWrites,
],
];
}
private function rowError(int $row, string $message): string
{
return sprintf('Row %d: %s', $row, $message);
}
private function invalidImportRow(array $row, string $reason): array
{
return [
'row' => (int)($row['row'] ?? 0),
'sku' => (string)($row['sku'] ?? ''),
'website' => (string)($row['website'] ?? ''),
'combined_qty_from' => $row['combined_qty_from'] ?? '',
'pricing_method' => (string)($row['pricing_method'] ?? ''),
'value' => $row['value'] ?? '',
'reason' => $reason,
];
}
private function invalidDeleteRow(array $row, string $reason): array
{
return [
'row' => (int)($row['row'] ?? 0),
'sku' => (string)($row['sku'] ?? ''),
'website' => (string)($row['website'] ?? ''),
'reason' => $reason,
];
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\MixStepPricing;
use Magento\Framework\Exception\LocalizedException;
class DeleteService
{
public function __construct(
private readonly SpreadsheetReader $reader,
private readonly BatchValidator $validator,
private readonly AttributeWriter $attributeWriter
) {
}
public function validate(string $path): array
{
return $this->validator->validateDelete($this->reader->readDelete($path));
}
/**
* @throws LocalizedException
*/
public function run(string $path): array
{
$result = $this->validate($path);
if (!$result['valid']) {
throw new LocalizedException(__('Validation failed. No prices were deleted.'));
}
if ($result['groups'] === []) {
throw new LocalizedException(__('There are no existing configurable products to delete.'));
}
return $this->attributeWriter->write($result['groups'], true);
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\MixStepPricing;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
class FileUploader
{
private const TARGET_DIRECTORY = 'esun_mix_step_pricing';
public function __construct(
private readonly UploaderFactory $uploaderFactory,
private readonly Filesystem $filesystem
) {
}
/**
* @throws LocalizedException
*/
public function upload(string $fileId): string
{
$directory = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_IMPORT_EXPORT);
$directory->create(self::TARGET_DIRECTORY);
$uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
$uploader->setAllowedExtensions(['xlsx', 'xls']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$result = $uploader->save($directory->getAbsolutePath(self::TARGET_DIRECTORY));
if (!$result || empty($result['path']) || empty($result['file'])) {
throw new LocalizedException(__('The Excel file could not be uploaded.'));
}
return rtrim((string)$result['path'], DIRECTORY_SEPARATOR)
. DIRECTORY_SEPARATOR
. ltrim((string)$result['file'], DIRECTORY_SEPARATOR);
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\MixStepPricing;
use Magento\Framework\Exception\LocalizedException;
class ImportService
{
public function __construct(
private readonly SpreadsheetReader $reader,
private readonly BatchValidator $validator,
private readonly AttributeWriter $attributeWriter
) {
}
public function validate(string $path): array
{
return $this->validator->validateImport($this->reader->readImport($path));
}
/**
* @throws LocalizedException
*/
public function run(string $path): array
{
$result = $this->validate($path);
if (!$result['valid']) {
throw new LocalizedException(__('Validation failed. No prices were changed.'));
}
return $this->attributeWriter->write($result['groups'], false);
}
}
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\MixStepPricing;
use Magento\Customer\Model\Group;
use Magento\Framework\Exception\LocalizedException;
class RuleNormalizer
{
public const PRICE_TYPE_PERCENT = 'percent';
public const PRICE_TYPE_FIXED = 'fixed';
/**
* Normalize rows submitted by the product edit form.
*/
public function normalize(array $rows): array
{
$normalized = [];
foreach ($rows as $row) {
if (!is_array($row) || !empty($row['delete'])) {
continue;
}
$quantity = (int)($row['qty'] ?? 0);
$value = round((float)($row['value'] ?? 0), 4);
$priceType = (string)($row['price_type'] ?? self::PRICE_TYPE_PERCENT);
if (!$this->isValid($quantity, $priceType, $value)) {
continue;
}
$normalized[] = [
'enabled' => !isset($row['enabled']) || (bool)$row['enabled'],
'customer_group_id' => isset($row['customer_group_id']) && $row['customer_group_id'] !== ''
? (int)$row['customer_group_id']
: Group::CUST_GROUP_ALL,
'qty' => $quantity,
'price_type' => $priceType,
'value' => $value,
];
}
usort($normalized, static function (array $left, array $right): int {
return [$left['customer_group_id'], $left['qty']] <=> [$right['customer_group_id'], $right['qty']];
});
return $normalized;
}
/**
* Convert one validated spreadsheet row to the persisted rule format.
*
* @throws LocalizedException
*/
public function fromSpreadsheetRow(array $row): array
{
$quantityValue = $row['combined_qty_from'] ?? null;
if (!is_numeric($quantityValue) || (float)$quantityValue !== (float)(int)$quantityValue) {
throw new LocalizedException(__('Combined Qty From must be an integer.'));
}
$quantity = (int)$quantityValue;
if ($quantity < 1) {
throw new LocalizedException(__('Combined Qty From must be at least 1.'));
}
$method = strtolower(trim((string)($row['pricing_method'] ?? '')));
$priceType = match ($method) {
'discount percentage' => self::PRICE_TYPE_PERCENT,
'unit price' => self::PRICE_TYPE_FIXED,
default => throw new LocalizedException(
__('Pricing Method must be Discount Percentage or Unit Price.')
),
};
$valueInput = $row['value'] ?? null;
if (!is_numeric($valueInput)) {
throw new LocalizedException(__('Discount %% / Unit Price must be numeric.'));
}
$value = round((float)$valueInput, 4);
if ($value <= 0) {
throw new LocalizedException(__('Discount %% / Unit Price must be greater than 0.'));
}
if ($priceType === self::PRICE_TYPE_PERCENT && $value >= 100) {
throw new LocalizedException(__('Discount Percentage must be less than 100.'));
}
return [
'enabled' => true,
'customer_group_id' => Group::CUST_GROUP_ALL,
'qty' => $quantity,
'price_type' => $priceType,
'value' => $value,
];
}
private function isValid(int $quantity, string $priceType, float $value): bool
{
if ($quantity < 1 || $value <= 0 || !in_array($priceType, [self::PRICE_TYPE_PERCENT, self::PRICE_TYPE_FIXED], true)) {
return false;
}
return $priceType !== self::PRICE_TYPE_PERCENT || $value < 100;
}
}
@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\MixStepPricing;
use Magento\Framework\Exception\LocalizedException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
class SpreadsheetReader
{
public const IMPORT_SHEET = '批量导入模板';
public const DELETE_SHEET = '批量删除模板';
private const MAX_ROWS = 5000;
private const IMPORT_HEADERS = [
'sku',
'website',
'Combined Qty From',
'Pricing Method',
'Discount % / Unit Price',
];
private const DELETE_HEADERS = ['sku', 'website'];
/**
* @throws LocalizedException
*/
public function readImport(string $path): array
{
return $this->read($path, self::IMPORT_SHEET, self::IMPORT_HEADERS, static function (array $values, int $row): array {
return [
'row' => $row,
'sku' => trim((string)$values[0]),
'website' => trim((string)$values[1]),
'combined_qty_from' => $values[2],
'pricing_method' => trim((string)$values[3]),
'value' => $values[4],
];
});
}
/**
* @throws LocalizedException
*/
public function readDelete(string $path): array
{
return $this->read($path, self::DELETE_SHEET, self::DELETE_HEADERS, static function (array $values, int $row): array {
return [
'row' => $row,
'sku' => trim((string)$values[0]),
'website' => trim((string)$values[1]),
];
});
}
/**
* @throws LocalizedException
*/
private function read(string $path, string $sheetName, array $headers, callable $mapper): array
{
try {
$spreadsheet = IOFactory::load($path);
} catch (\Throwable $exception) {
throw new LocalizedException(__('The Excel file could not be read: %1', $exception->getMessage()));
}
try {
$sheet = $spreadsheet->getSheetByName($sheetName);
if ($sheet === null) {
throw new LocalizedException(__('The workbook must contain a "%1" worksheet.', $sheetName));
}
foreach ($headers as $index => $expected) {
$actual = trim((string)$sheet->getCell(Coordinate::stringFromColumnIndex($index + 1) . '1')->getValue());
if ($actual !== $expected) {
throw new LocalizedException(
__('Invalid header in column %1. Expected "%2", found "%3".', $index + 1, $expected, $actual)
);
}
}
$highestRow = $sheet->getHighestDataRow();
if ($highestRow - 1 > self::MAX_ROWS) {
throw new LocalizedException(__('The file contains more than %1 data rows.', self::MAX_ROWS));
}
$rows = [];
for ($row = 2; $row <= $highestRow; $row++) {
$values = [];
foreach (array_keys($headers) as $index) {
$cell = $sheet->getCell(Coordinate::stringFromColumnIndex($index + 1) . $row);
if ($cell->isFormula()) {
throw new LocalizedException(__('Row %1 contains a formula. Use plain values only.', $row));
}
$values[] = $cell->getValue();
}
if (count(array_filter($values, static fn(mixed $value): bool => $value !== null && trim((string)$value) !== '')) === 0) {
continue;
}
$rows[] = $mapper($values, $row);
}
if ($rows === []) {
throw new LocalizedException(__('The worksheet contains no data rows.'));
}
return $rows;
} finally {
$spreadsheet->disconnectWorksheets();
}
}
}
@@ -0,0 +1,132 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\MixStepPricing;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class TemplateGenerator
{
public function createImport(): string
{
$spreadsheet = $this->createBase(
SpreadsheetReader::IMPORT_SHEET,
['sku', 'website', 'Combined Qty From', 'Pricing Method', 'Discount % / Unit Price'],
[24, 14, 24, 28, 30]
);
$sheet = $spreadsheet->getActiveSheet();
$this->addListValidation($sheet, 'B2:B1000', '"us,au,eu,uk"');
$this->addListValidation($sheet, 'D2:D1000', '"Discount Percentage,Unit Price"');
$sheet->getStyle('C2:C1000')->getNumberFormat()->setFormatCode('0');
$sheet->getStyle('E2:E1000')->getNumberFormat()->setFormatCode('0.0000');
$this->addGuide($spreadsheet, [
['Function', 'Use only with Batch Import.'],
['Scope', 'Each sku + website replaces the complete existing tier set for every Store View in that website.'],
['website', 'Lowercase us, au, eu, or uk.'],
['Combined Qty From', 'Integer 1 or greater; unique within each sku + website.'],
['Pricing Method', 'Discount Percentage or Unit Price.'],
['Value', 'Discount Percentage must be greater than 0 and less than 100; Unit Price must be greater than 0.'],
]);
return $this->toString($spreadsheet);
}
public function createDelete(): string
{
$spreadsheet = $this->createBase(
SpreadsheetReader::DELETE_SHEET,
['sku', 'website'],
[28, 18]
);
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle('A1:B1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('9C0006');
$this->addListValidation($sheet, 'B2:B1000', '"us,au,eu,uk"');
$this->addGuide($spreadsheet, [
['Function', 'Use only with Batch Delete.'],
['Effect', 'Each row deletes all Mix Step Pricing for the sku + website across every Store View.'],
['website', 'Lowercase us, au, eu, or uk.'],
['Warning', 'Deleting a single tier is not supported. Use Batch Import to replace a partial tier set.'],
]);
return $this->toString($spreadsheet);
}
private function createBase(string $sheetName, array $headers, array $widths): Spreadsheet
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle($sheetName);
$sheet->fromArray($headers, null, 'A1');
$lastColumn = chr(64 + count($headers));
$sheet->getStyle('A1:' . $lastColumn . '1000')->applyFromArray([
'borders' => ['allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => 'B7C9D6'],
]],
]);
$sheet->getStyle('A1:' . $lastColumn . '1')->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '17365D']],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
]);
$sheet->getRowDimension(1)->setRowHeight(24);
foreach ($widths as $index => $width) {
$sheet->getColumnDimension(chr(65 + $index))->setWidth($width);
}
$sheet->freezePane('A2');
$sheet->setShowGridlines(false);
return $spreadsheet;
}
private function addListValidation($sheet, string $range, string $formula): void
{
$validation = $sheet->getCell(explode(':', $range)[0])->getDataValidation();
$validation->setType(DataValidation::TYPE_LIST);
$validation->setErrorStyle(DataValidation::STYLE_STOP);
$validation->setAllowBlank(false);
$validation->setShowErrorMessage(true);
$validation->setShowDropDown(true);
$validation->setFormula1($formula);
$sheet->setDataValidation($range, $validation);
}
private function addGuide(Spreadsheet $spreadsheet, array $rows): void
{
$guide = $spreadsheet->createSheet();
$guide->setTitle('Instructions');
$guide->fromArray([['Item', 'Rule'], ...$rows], null, 'A1');
$guide->getStyle('A1:B1')->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '17365D']],
]);
$guide->getColumnDimension('A')->setWidth(24);
$guide->getColumnDimension('B')->setWidth(90);
$guide->getStyle('A1:B' . (count($rows) + 1))->getAlignment()->setWrapText(true);
$guide->getStyle('A1:B' . (count($rows) + 1))->applyFromArray([
'borders' => ['allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => 'B7C9D6'],
]],
]);
$guide->setShowGridlines(false);
$spreadsheet->setActiveSheetIndex(0);
}
private function toString(Spreadsheet $spreadsheet): string
{
$temporary = fopen('php://temp', 'w+b');
(new Xlsx($spreadsheet))->save($temporary);
rewind($temporary);
$contents = stream_get_contents($temporary);
fclose($temporary);
$spreadsheet->disconnectWorksheets();
return (string)$contents;
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\MixStepPricing;
use Magento\Backend\Model\Session;
class ValidationState
{
private const PREFIX = 'esun_mix_step_pricing_';
private const STATE_VERSION = 2;
public function __construct(private readonly Session $session)
{
}
public function save(string $type, string $path, array $result): void
{
$validRows = (array)($result['valid_rows'] ?? []);
$invalidRows = (array)($result['invalid_rows'] ?? []);
$preview = array_slice($validRows, 0, 100);
$invalidPreview = array_slice($invalidRows, 0, 100);
$this->session->setData(self::PREFIX . $type, [
'version' => self::STATE_VERSION,
'path' => $path,
'valid' => (bool)$result['valid'],
'stats' => $result['stats'],
'errors' => $result['errors'],
'warnings' => $result['warnings'],
'preview' => $preview,
'preview_truncated' => count($validRows) > 100,
'invalid_preview' => $invalidPreview,
'invalid_preview_truncated' => count($invalidRows) > 100,
]);
}
public function get(string $type): array
{
$state = (array)$this->session->getData(self::PREFIX . $type);
if ($state !== [] && (int)($state['version'] ?? 0) !== self::STATE_VERSION) {
$this->clear($type);
return [];
}
return $state;
}
public function clear(string $type): void
{
$this->session->unsetData(self::PREFIX . $type);
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\MixStepPricing;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
class WebsiteResolver
{
private const WEBSITE_CODE_MAP = [
'us' => 'us_site',
'au' => 'au',
'eu' => 'eu',
'uk' => 'uk',
];
private array $resolved = [];
public function __construct(private readonly StoreManagerInterface $storeManager)
{
}
/**
* @throws LocalizedException
*/
public function resolve(string $alias): array
{
if ($alias !== strtolower($alias) || !isset(self::WEBSITE_CODE_MAP[$alias])) {
throw new LocalizedException(__('Website must be one of: us, au, eu, uk.'));
}
if (isset($this->resolved[$alias])) {
return $this->resolved[$alias];
}
try {
$website = $this->storeManager->getWebsite(self::WEBSITE_CODE_MAP[$alias]);
} catch (\Throwable) {
throw new LocalizedException(__('Magento website for "%1" is not configured.', $alias));
}
$storeIds = array_values(array_filter(
array_map('intval', $website->getStoreIds()),
static fn(int $storeId): bool => $storeId > 0
));
if ($storeIds === []) {
throw new LocalizedException(__('Website "%1" has no Store Views.', $alias));
}
return $this->resolved[$alias] = [
'alias' => $alias,
'code' => (string)$website->getCode(),
'website_id' => (int)$website->getId(),
'store_ids' => $storeIds,
];
}
}
@@ -0,0 +1,133 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model;
use Magento\Framework\Module\Dir\Reader as ModuleDirReader;
use Magento\Framework\Serialize\Serializer\Json;
class PrintingParameter
{
private ?array $data = null;
private ?array $groups = null;
public function __construct(
private readonly ModuleDirReader $moduleDirReader,
private readonly Json $json
) {
}
public function getByProductName(string $productName): array
{
$data = $this->getData();
if (!$data) {
return [];
}
$productName = trim($productName);
if ($productName === '') {
return [];
}
if (isset($data[$productName]) && is_array($data[$productName])) {
return $this->withGroupConfig($data[$productName]);
}
$normalizedProductName = $this->normalizeName($productName);
foreach ($data as $name => $parameters) {
if ($this->normalizeName((string)$name) === $normalizedProductName && is_array($parameters)) {
return $this->withGroupConfig($parameters);
}
}
uksort($data, static fn (string $a, string $b): int => strlen($b) <=> strlen($a));
foreach ($data as $name => $parameters) {
$normalizedName = $this->normalizeName((string)$name);
if ($normalizedName !== ''
&& (str_contains($normalizedProductName, $normalizedName) || str_contains($normalizedName, $normalizedProductName))
&& is_array($parameters)
) {
return $this->withGroupConfig($parameters);
}
}
return [];
}
/**
* @return array<string, array<string, array{icon: string, items: array}>>
*/
public function getAll(): array
{
$result = [];
foreach ($this->getData() as $name => $parameters) {
if (is_array($parameters)) {
$result[(string)$name] = $this->withGroupConfig($parameters);
}
}
return $result;
}
private function getData(): array
{
if ($this->data !== null) {
return $this->data;
}
$path = $this->moduleDirReader->getModuleDir('', 'Esun_Catalog') . '/data/printing-parameters.json';
if (!is_file($path)) {
return $this->data = [];
}
try {
$decoded = $this->json->unserialize((string)file_get_contents($path));
return $this->data = is_array($decoded) ? $decoded : [];
} catch (\InvalidArgumentException) {
return $this->data = [];
}
}
private function getGroups(): array
{
if ($this->groups !== null) {
return $this->groups;
}
$path = $this->moduleDirReader->getModuleDir('', 'Esun_Catalog') . '/data/printing-parameter-groups.json';
if (!is_file($path)) {
return $this->groups = [];
}
try {
$decoded = $this->json->unserialize((string)file_get_contents($path));
return $this->groups = is_array($decoded) ? $decoded : [];
} catch (\InvalidArgumentException) {
return $this->groups = [];
}
}
private function withGroupConfig(array $parameters): array
{
$groups = $this->getGroups();
$result = [];
foreach ($parameters as $groupName => $items) {
if (!is_array($items)) {
continue;
}
$result[(string)$groupName] = [
'icon' => (string)($groups[$groupName]['icon'] ?? ''),
'items' => $items,
];
}
return $result;
}
private function normalizeName(string $name): string
{
$name = strtolower($name);
return preg_replace('/[^a-z0-9]+/', '', $name) ?: '';
}
}
@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\PrintingParameter;
use Magento\Framework\Exception\LocalizedException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class ExcelParser
{
private const PRODUCT_ROW = 2;
private const DATA_START_ROW = 3;
private const PARAMETER_COLUMN = 3;
private const PRODUCT_START_COLUMN = 4;
/**
* @return array<string, array<string, array<string, string>>>
* @throws LocalizedException
*/
public function parse(string $filePath): array
{
if (!is_file($filePath)) {
throw new LocalizedException(__('The uploaded printing parameter Excel file was not found.'));
}
try {
$spreadsheet = IOFactory::load($filePath);
} catch (\Throwable $exception) {
throw new LocalizedException(__('Unable to read the printing parameter Excel file: %1', $exception->getMessage()));
}
$sheet = $spreadsheet->getActiveSheet();
$highestColumnIndex = Coordinate::columnIndexFromString($sheet->getHighestColumn());
$highestRow = $sheet->getHighestRow();
$products = $this->getProducts($sheet, $highestColumnIndex);
if (!$products) {
throw new LocalizedException(__('No product names were found from D2 onward in the printing parameter Excel file.'));
}
$groupByRow = $this->getGroupRowMap($sheet);
$data = [];
$currentGroup = '';
for ($row = self::DATA_START_ROW; $row <= $highestRow; $row++) {
$group = $groupByRow[$row] ?? $this->readCell($sheet, 1, $row);
if ($group !== '') {
$currentGroup = $group;
}
if ($currentGroup === '') {
continue;
}
$parameter = $this->readCell($sheet, self::PARAMETER_COLUMN, $row);
if ($parameter === '') {
continue;
}
foreach ($products as $column => $productName) {
$value = $this->readCell($sheet, $column, $row);
if ($value === '') {
continue;
}
$data[$productName][$currentGroup] ??= [];
$data[$productName][$currentGroup][$parameter] = $value;
}
}
$spreadsheet->disconnectWorksheets();
return $data;
}
/**
* @return array<int, string>
*/
private function getProducts(Worksheet $sheet, int $highestColumnIndex): array
{
$products = [];
for ($column = self::PRODUCT_START_COLUMN; $column <= $highestColumnIndex; $column++) {
$productName = $this->readCell($sheet, $column, self::PRODUCT_ROW);
if ($productName !== '') {
$products[$column] = $productName;
}
}
return $products;
}
/**
* @return array<int, string>
*/
private function getGroupRowMap(Worksheet $sheet): array
{
$groups = [];
foreach ($sheet->getMergeCells() as $range) {
[$start, $end] = Coordinate::rangeBoundaries($range);
[$startColumn, $startRow] = $start;
[$endColumn, $endRow] = $end;
if ($startColumn !== 1 || $endColumn !== 1 || $endRow < self::DATA_START_ROW) {
continue;
}
$group = $this->readCell($sheet, 1, $startRow);
if ($group === '') {
continue;
}
for ($row = max($startRow, self::DATA_START_ROW); $row <= $endRow; $row++) {
$groups[$row] = $group;
}
}
return $groups;
}
private function readCell(Worksheet $sheet, int $column, int $row): string
{
$cell = $sheet->getCell(Coordinate::stringFromColumnIndex($column) . $row);
$value = $cell->getFormattedValue();
if ($value === null || $value === '') {
$value = $cell->getCalculatedValue();
}
return $this->normalize((string)$value);
}
private function normalize(string $value): string
{
$value = str_replace(["\r\n", "\r"], "\n", $value);
$lines = array_map(function (string $line): string {
$line = trim(preg_replace('/[ \t]+/', ' ', $line) ?: '');
return $this->cleanNumber($line);
}, explode("\n", $value));
$lines = array_values(array_filter($lines, static fn (string $line): bool => $line !== ''));
return implode("\n", $lines);
}
private function cleanNumber(string $value): string
{
if (!is_numeric($value) || !str_contains($value, '.')) {
return $value;
}
[, $decimal] = explode('.', $value, 2);
if (strlen($decimal) <= 8) {
return $value;
}
return rtrim(rtrim(sprintf('%.8F', (float)$value), '0'), '.');
}
}
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\Product\Attribute\Backend;
use Magento\Catalog\Model\ImageUploader;
use Esun\Catalog\Model\CertificationFileUploader;
use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend;
use Magento\Framework\DataObject;
use Magento\Framework\Serialize\Serializer\Json;
class JsonRows extends AbstractBackend
{
private const IMAGE_FIELDS = ['icon', 'image'];
private const FILE_FIELDS = ['file'];
private const UPLOADER_BASE_PATH = 'esun/catalog/product-detail';
public function __construct(
private readonly Json $json,
private readonly ImageUploader $imageUploader,
private readonly CertificationFileUploader $certificationFileUploader
) {
}
public function afterLoad($object): self
{
$attributeCode = $this->getAttribute()->getAttributeCode();
$value = $object->getData($attributeCode);
if (is_string($value) && trim($value) !== '') {
try {
$decoded = $this->json->unserialize($value);
$object->setData($attributeCode, is_array($decoded) ? $decoded : []);
} catch (\InvalidArgumentException) {
$object->setData($attributeCode, []);
}
}
return parent::afterLoad($object);
}
public function beforeSave($object): self
{
$attributeCode = $this->getAttribute()->getAttributeCode();
$value = $object->getData($attributeCode);
if (is_array($value)) {
$value = $this->prepareRows($value, (string)$object->getSku());
$object->setData($attributeCode, $this->json->serialize($value));
}
return parent::beforeSave($object);
}
private function prepareRows(array $rows, string $sku): array
{
$prepared = [];
foreach ($rows as $row) {
if (!is_array($row) || !empty($row['delete'])) {
continue;
}
unset($row['record_id'], $row['initialize'], $row['delete']);
$row['enabled'] = !isset($row['enabled']) || (bool)$row['enabled'];
$row['position'] = (int)($row['position'] ?? 0);
foreach (self::IMAGE_FIELDS as $field) {
if (array_key_exists($field, $row)) {
$row[$field] = $this->normalizeImageValue($row[$field]);
}
}
foreach (self::FILE_FIELDS as $field) {
if (array_key_exists($field, $row)) {
$row[$field] = $this->normalizeFileValue($row[$field], $sku);
}
}
$prepared[] = $row;
}
usort($prepared, static fn (array $a, array $b): int => ((int)$a['position'] <=> (int)$b['position']));
return array_values($prepared);
}
private function normalizeImageValue(mixed $value): string
{
if (is_array($value)) {
$image = reset($value);
if ($image instanceof DataObject) {
$image = $image->getData();
}
if (is_array($image)) {
$file = (string)($image['file'] ?? $image['name'] ?? '');
$url = (string)($image['url'] ?? '');
return $this->moveTmpImage($file, $url);
}
}
if (is_string($value)) {
return $this->stripMediaUrl($value);
}
return '';
}
private function normalizeFileValue(mixed $value, string $sku): string
{
if (is_array($value)) {
$file = reset($value);
if ($file instanceof DataObject) {
$file = $file->getData();
}
if (is_array($file)) {
return $this->moveTmpFile((string)($file['file'] ?? $file['name'] ?? $file['url'] ?? ''), $sku);
}
}
if (is_string($value)) {
return $this->moveTmpFile($this->stripMediaUrl($value), $sku);
}
return '';
}
private function moveTmpFile(string $file, string $sku): string
{
$file = ltrim($file, '/');
if ($file === '') {
return '';
}
try {
return $this->certificationFileUploader->moveFileFromTmp($file, $sku);
} catch (\Exception) {
return $file;
}
}
private function moveTmpImage(string $file, string $url): string
{
$file = ltrim($file, '/');
if ($file === '' && $url !== '') {
$file = basename(parse_url($url, PHP_URL_PATH) ?: '');
}
if ($file === '') {
return '';
}
if (str_starts_with($file, self::UPLOADER_BASE_PATH . '/')) {
return $file;
}
if (str_starts_with($file, 'tmp/' . self::UPLOADER_BASE_PATH . '/')) {
$file = basename($file);
}
try {
return $this->imageUploader->moveFileFromTmp($file, true);
} catch (\Exception) {
return $this->stripMediaUrl($url) ?: $file;
}
}
private function stripMediaUrl(string $value): string
{
$path = parse_url($value, PHP_URL_PATH);
if (!$path) {
return ltrim($value, '/');
}
$marker = '/media/';
$position = strpos($path, $marker);
return $position !== false ? ltrim(substr($path, $position + strlen($marker)), '/') : ltrim($path, '/');
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\Product\Attribute\Backend;
use Esun\Catalog\Model\MixStepPricing\RuleNormalizer;
use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend;
use Magento\Framework\Serialize\Serializer\Json;
class MixStepPrices extends AbstractBackend
{
public function __construct(
private readonly Json $json,
private readonly RuleNormalizer $ruleNormalizer
) {
}
public function afterLoad($object): self
{
$attributeCode = $this->getAttribute()->getAttributeCode();
$value = $object->getData($attributeCode);
if (is_string($value) && trim($value) !== '') {
try {
$decoded = $this->json->unserialize($value);
$object->setData($attributeCode, is_array($decoded) ? $decoded : []);
} catch (\InvalidArgumentException) {
$object->setData($attributeCode, []);
}
}
return parent::afterLoad($object);
}
public function beforeSave($object): self
{
$attributeCode = $this->getAttribute()->getAttributeCode();
$value = $object->getData($attributeCode);
if (is_array($value)) {
$object->setData($attributeCode, $this->json->serialize($this->ruleNormalizer->normalize($value)));
}
return parent::beforeSave($object);
}
}
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\Product;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Pricing\Price\FinalPrice;
use Magento\Catalog\Pricing\Price\RegularPrice;
/**
* Resolves prices for product cards, including out-of-stock configurables.
*
* Magento's configurable price resolver only considers saleable children. When
* every variation is out of stock it returns zero, even though the price index
* and the associated products still contain valid catalogue prices.
*/
class CardPriceResolver
{
/** @var array<string, array{final: float, regular: float}> */
private array $prices = [];
public function getFinalPrice(Product $product): float
{
return $this->resolve($product)['final'];
}
public function getRegularPrice(Product $product): float
{
return $this->resolve($product)['regular'];
}
/**
* @return array{final: float, regular: float}
*/
private function resolve(Product $product): array
{
$key = (int) $product->getStoreId() . ':' . (int) $product->getId();
if (isset($this->prices[$key])) {
return $this->prices[$key];
}
$priceInfo = $product->getPriceInfo();
$finalPrice = (float) $priceInfo->getPrice(FinalPrice::PRICE_CODE)->getAmount()->getValue();
$regularPrice = (float) $priceInfo->getPrice(RegularPrice::PRICE_CODE)->getAmount()->getValue();
if ($finalPrice > 0 || $product->getTypeId() !== 'configurable') {
return $this->prices[$key] = [
'final' => $finalPrice,
'regular' => max($regularPrice, $finalPrice),
];
}
// Product collections used by category and homepage cards already join
// the price index. Its min_price remains valid for an out-of-stock
// configurable, unlike the runtime configurable price resolver.
$indexedMinPrice = (float) $product->getData('min_price');
if ($indexedMinPrice > 0) {
$finalPrice = $indexedMinPrice;
}
// Collections without price-index data (for example a newly loaded
// menu product) still get a safe fallback from enabled variations.
$fallbackRegularPrice = 0.0;
foreach ($product->getTypeInstance()->getUsedProducts($product) as $child) {
if ((int) $child->getStatus() !== Product\Attribute\Source\Status::STATUS_ENABLED) {
continue;
}
$childFinalPrice = (float) $child->getPriceInfo()
->getPrice(FinalPrice::PRICE_CODE)
->getAmount()
->getValue();
if ($childFinalPrice <= 0 || ($finalPrice > 0 && $childFinalPrice > $finalPrice)) {
continue;
}
$finalPrice = $childFinalPrice;
$fallbackRegularPrice = (float) $child->getPriceInfo()
->getPrice(RegularPrice::PRICE_CODE)
->getAmount()
->getValue();
}
return $this->prices[$key] = [
'final' => $finalPrice,
'regular' => max($regularPrice, $fallbackRegularPrice, $finalPrice),
];
}
}
@@ -0,0 +1,176 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ProductRecommendation;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
class BatchValidator
{
public function __construct(
private readonly ProductRepositoryInterface $productRepository,
private readonly WebsiteResolver $websiteResolver
) {
}
public function validate(array $rows): array
{
$errors = [];
$groups = [];
$products = [];
foreach ($rows as $row) {
$rowNumber = (int)($row['row'] ?? 0);
$sourceSku = trim((string)($row['source_sku'] ?? ''));
$websiteAlias = trim((string)($row['website'] ?? ''));
$recommendedSku = trim((string)($row['recommended_sku'] ?? ''));
$sortOrderValue = $row['sort_order'] ?? '';
if ($sourceSku === '') {
$errors[] = $this->rowError($rowNumber, 'source_sku is required.');
continue;
}
try {
$website = $this->websiteResolver->resolve($websiteAlias);
$source = $products[$sourceSku] ??= $this->productRepository->get($sourceSku, false, 0);
} catch (NoSuchEntityException) {
$errors[] = $this->rowError($rowNumber, sprintf('Source SKU "%s" does not exist.', $sourceSku));
continue;
} catch (LocalizedException $exception) {
$errors[] = $this->rowError($rowNumber, $exception->getMessage());
continue;
}
$websiteId = (int)$website['website_id'];
if ($websiteId > 0
&& !in_array($websiteId, array_map('intval', (array)$source->getWebsiteIds()), true)
) {
$errors[] = $this->rowError(
$rowNumber,
sprintf('Source SKU "%s" is not assigned to website "%s".', $sourceSku, $websiteAlias)
);
continue;
}
$key = strtolower($sourceSku) . '|' . $websiteAlias;
if (!isset($groups[$key])) {
$groups[$key] = [
'source_sku' => $sourceSku,
'product_id' => (int)$source->getId(),
'website' => $websiteAlias,
'website_id' => (int)$website['website_id'],
'items' => [],
'empty_rows' => [],
];
}
if ($recommendedSku === '') {
if ($sortOrderValue !== null && trim((string)$sortOrderValue) !== '') {
$errors[] = $this->rowError($rowNumber, 'sort_order must be blank when recommended_sku is blank.');
}
$groups[$key]['empty_rows'][] = $rowNumber;
continue;
}
if (strcasecmp($sourceSku, $recommendedSku) === 0) {
$errors[] = $this->rowError($rowNumber, 'A product cannot recommend itself.');
continue;
}
if (!$this->isNonNegativeInteger($sortOrderValue)) {
$errors[] = $this->rowError($rowNumber, 'sort_order must be a non-negative integer.');
continue;
}
try {
$recommended = $products[$recommendedSku]
??= $this->productRepository->get($recommendedSku, false, 0);
} catch (NoSuchEntityException) {
$errors[] = $this->rowError(
$rowNumber,
sprintf('Recommended SKU "%s" does not exist.', $recommendedSku)
);
continue;
}
if ($websiteId > 0
&& !in_array($websiteId, array_map('intval', (array)$recommended->getWebsiteIds()), true)
) {
$errors[] = $this->rowError(
$rowNumber,
sprintf('Recommended SKU "%s" is not assigned to website "%s".', $recommendedSku, $websiteAlias)
);
continue;
}
$sortOrder = (int)$sortOrderValue;
foreach ($groups[$key]['items'] as $item) {
if ((int)$item['product_id'] === (int)$recommended->getId()) {
$errors[] = $this->rowError($rowNumber, sprintf('Recommended SKU "%s" is duplicated.', $recommendedSku));
continue 2;
}
if ((int)$item['sort_order'] === $sortOrder) {
$errors[] = $this->rowError($rowNumber, sprintf('sort_order %d is duplicated in this group.', $sortOrder));
continue 2;
}
}
$groups[$key]['items'][] = [
'row' => $rowNumber,
'product_id' => (int)$recommended->getId(),
'sku' => $recommendedSku,
'sort_order' => $sortOrder,
];
}
$preview = [];
foreach ($groups as $key => &$group) {
if ($group['empty_rows'] !== [] && $group['items'] !== []) {
foreach ($group['empty_rows'] as $rowNumber) {
$errors[] = $this->rowError(
(int)$rowNumber,
'An empty-set row cannot be combined with recommended products in the same group.'
);
}
}
if (count($group['empty_rows']) > 1) {
$errors[] = $this->rowError(
(int)$group['empty_rows'][1],
'The empty recommendation set is duplicated.'
);
}
usort($group['items'], static fn(array $left, array $right): int => $left['sort_order'] <=> $right['sort_order']);
$group['product_ids'] = array_column($group['items'], 'product_id');
$preview[] = [
'source_sku' => $group['source_sku'],
'website' => $group['website'],
'recommended_skus' => implode(', ', array_column($group['items'], 'sku')),
'count' => count($group['items']),
];
unset($group['items'], $group['empty_rows']);
}
unset($group);
return [
'valid' => $errors === [],
'errors' => $errors,
'groups' => array_values($groups),
'preview' => $preview,
'stats' => [
'rows' => count($rows),
'groups' => count($groups),
'recommendations' => array_sum(array_column($preview, 'count')),
],
];
}
private function isNonNegativeInteger(mixed $value): bool
{
return preg_match('/^\d+$/', trim((string)$value)) === 1;
}
private function rowError(int $row, string $message): string
{
return sprintf('Row %d: %s', $row, $message);
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ProductRecommendation;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
class FileUploader
{
private const TARGET_DIRECTORY = 'esun_product_recommendations';
public function __construct(
private readonly UploaderFactory $uploaderFactory,
private readonly Filesystem $filesystem
) {
}
public function upload(string $fileId): string
{
$directory = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_IMPORT_EXPORT);
$directory->create(self::TARGET_DIRECTORY);
$uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
$uploader->setAllowedExtensions(['xlsx', 'xls']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$result = $uploader->save($directory->getAbsolutePath(self::TARGET_DIRECTORY));
if (!$result || empty($result['path']) || empty($result['file'])) {
throw new LocalizedException(__('The Excel file could not be uploaded.'));
}
return rtrim((string)$result['path'], DIRECTORY_SEPARATOR)
. DIRECTORY_SEPARATOR . ltrim((string)$result['file'], DIRECTORY_SEPARATOR);
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ProductRecommendation;
use Magento\Framework\Exception\LocalizedException;
class ImportService
{
public function __construct(
private readonly SpreadsheetReader $reader,
private readonly BatchValidator $validator,
private readonly Writer $writer
) {
}
public function validate(string $path): array
{
return $this->validator->validate($this->reader->read($path));
}
public function run(string $path): array
{
$result = $this->validate($path);
if (!$result['valid']) {
throw new LocalizedException(__('Validation failed. No recommendations were changed.'));
}
return $this->writer->replaceGroups($result['groups']);
}
}
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ProductRecommendation;
use Magento\Framework\App\ResourceConnection;
class RecommendationRepository
{
private const SET_TABLE = 'esun_product_recommendation_set';
private const ITEM_TABLE = 'esun_product_recommendation_item';
public function __construct(private readonly ResourceConnection $resource)
{
}
/**
* Returns null when the scope inherits its fallback and an array (including an empty one) for an explicit set.
*/
public function getProductIds(int $productId, int $websiteId): ?array
{
$connection = $this->resource->getConnection();
$setTable = $this->resource->getTableName(self::SET_TABLE);
$itemTable = $this->resource->getTableName(self::ITEM_TABLE);
$setId = $connection->fetchOne(
$connection->select()
->from($setTable, ['set_id'])
->where('product_id = ?', $productId)
->where('website_id = ?', $websiteId)
);
if ($setId === false) {
return null;
}
return array_map('intval', $connection->fetchCol(
$connection->select()
->from($itemTable, ['recommended_product_id'])
->where('set_id = ?', (int)$setId)
->order(['sort_order ASC', 'item_id ASC'])
));
}
public function replace(int $productId, int $websiteId, array $productIds): void
{
$connection = $this->resource->getConnection();
$connection->beginTransaction();
try {
$this->doReplace($productId, $websiteId, $productIds);
$connection->commit();
} catch (\Throwable $exception) {
$connection->rollBack();
throw $exception;
}
}
public function replaceGroups(array $groups): void
{
$connection = $this->resource->getConnection();
$connection->beginTransaction();
try {
foreach ($groups as $group) {
$this->doReplace(
(int)$group['product_id'],
(int)$group['website_id'],
(array)$group['product_ids']
);
}
$connection->commit();
} catch (\Throwable $exception) {
$connection->rollBack();
throw $exception;
}
}
public function delete(int $productId, int $websiteId): void
{
$this->resource->getConnection()->delete(
$this->resource->getTableName(self::SET_TABLE),
['product_id = ?' => $productId, 'website_id = ?' => $websiteId]
);
}
private function doReplace(int $productId, int $websiteId, array $productIds): void
{
$connection = $this->resource->getConnection();
$setTable = $this->resource->getTableName(self::SET_TABLE);
$itemTable = $this->resource->getTableName(self::ITEM_TABLE);
$productIds = array_values(array_unique(array_map('intval', $productIds)));
$connection->insertOnDuplicate(
$setTable,
['product_id' => $productId, 'website_id' => $websiteId],
['product_id']
);
$setId = (int)$connection->fetchOne(
$connection->select()
->from($setTable, ['set_id'])
->where('product_id = ?', $productId)
->where('website_id = ?', $websiteId)
);
$connection->delete($itemTable, ['set_id = ?' => $setId]);
if ($productIds === []) {
return;
}
$rows = [];
foreach ($productIds as $position => $recommendedProductId) {
$rows[] = [
'set_id' => $setId,
'recommended_product_id' => $recommendedProductId,
'sort_order' => $position,
];
}
$connection->insertMultiple($itemTable, $rows);
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ProductRecommendation;
class Resolver
{
public function __construct(private readonly RecommendationRepository $repository)
{
}
/**
* Returns null when no recommendation set is configured.
*/
public function resolveProductIds(int $productId, int $websiteId): ?array
{
if ($websiteId > 0) {
$websiteIds = $this->repository->getProductIds($productId, $websiteId);
if ($websiteIds !== null) {
return $websiteIds;
}
}
return $this->repository->getProductIds($productId, 0);
}
}
@@ -0,0 +1,108 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ProductRecommendation;
use Magento\Framework\Exception\LocalizedException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
class SpreadsheetReader
{
public const SHEET = 'Product Recommendations';
public const MAX_RECOMMENDATIONS = 20;
private const MAX_ROWS = 5000;
private const FIXED_HEADERS = ['source_sku', 'website'];
public function read(string $path): array
{
try {
$spreadsheet = IOFactory::load($path);
} catch (\Throwable $exception) {
throw new LocalizedException(__('The Excel file could not be read: %1', $exception->getMessage()));
}
try {
$sheet = $spreadsheet->getSheetByName(self::SHEET);
if ($sheet === null) {
throw new LocalizedException(__('The workbook must contain a "%1" worksheet.', self::SHEET));
}
$headers = $this->getHeaders();
foreach ($headers as $index => $expected) {
$cell = Coordinate::stringFromColumnIndex($index + 1) . '1';
$actual = trim((string)$sheet->getCell($cell)->getValue());
if ($actual !== $expected) {
throw new LocalizedException(
__('Invalid header in column %1. Expected "%2", found "%3".', $index + 1, $expected, $actual)
);
}
}
$highestRow = $sheet->getHighestDataRow();
if ($highestRow - 1 > self::MAX_ROWS) {
throw new LocalizedException(__('The file contains more than %1 data rows.', self::MAX_ROWS));
}
$rows = [];
for ($rowNumber = 2; $rowNumber <= $highestRow; $rowNumber++) {
$values = [];
foreach (array_keys($headers) as $index) {
$cell = $sheet->getCell(Coordinate::stringFromColumnIndex($index + 1) . $rowNumber);
if ($cell->isFormula()) {
throw new LocalizedException(__('Row %1 contains a formula. Use plain values only.', $rowNumber));
}
$values[] = $cell->getValue();
}
if (count(array_filter(
$values,
static fn(mixed $value): bool => $value !== null && trim((string)$value) !== ''
)) === 0) {
continue;
}
$sourceSku = trim((string)$values[0]);
$website = trim((string)$values[1]);
$recommendedSkus = array_values(array_filter(
array_map(static fn(mixed $value): string => trim((string)$value), array_slice($values, 2)),
static fn(string $value): bool => $value !== ''
));
if ($recommendedSkus === []) {
$rows[] = [
'row' => $rowNumber,
'source_sku' => $sourceSku,
'website' => $website,
'recommended_sku' => '',
'sort_order' => '',
];
continue;
}
foreach ($recommendedSkus as $sortOrder => $recommendedSku) {
$rows[] = [
'row' => $rowNumber,
'source_sku' => $sourceSku,
'website' => $website,
'recommended_sku' => $recommendedSku,
'sort_order' => $sortOrder,
];
}
}
if ($rows === []) {
throw new LocalizedException(__('The worksheet contains no data rows.'));
}
return $rows;
} finally {
$spreadsheet->disconnectWorksheets();
}
}
private function getHeaders(): array
{
$headers = self::FIXED_HEADERS;
for ($position = 1; $position <= self::MAX_RECOMMENDATIONS; $position++) {
$headers[] = 'recommended_sku_' . $position;
}
return $headers;
}
}
@@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ProductRecommendation;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class TemplateGenerator
{
public function create(): string
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle(SpreadsheetReader::SHEET);
$headers = $this->getHeaders();
$lastColumn = Coordinate::stringFromColumnIndex(count($headers));
$sheet->fromArray($headers, null, 'A1');
$sheet->getStyle('A1:' . $lastColumn . '1')->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '17365D']],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
]);
$sheet->getColumnDimension('A')->setWidth(28);
$sheet->getColumnDimension('B')->setWidth(18);
for ($column = 3; $column <= count($headers); $column++) {
$sheet->getColumnDimensionByColumn($column)->setWidth(24);
}
$sheet->freezePane('A2');
$sheet->getStyle('A1:' . $lastColumn . '5000')->applyFromArray([
'borders' => ['allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => 'B7C9D6'],
]],
]);
$sheet->setShowGridlines(false);
$validation = $sheet->getCell('B2')->getDataValidation();
$validation->setType(DataValidation::TYPE_LIST)
->setErrorStyle(DataValidation::STYLE_STOP)
->setAllowBlank(false)
->setShowErrorMessage(true)
->setShowDropDown(true)
->setFormula1('"default,us,au,eu,uk"');
$sheet->setDataValidation('B2:B5000', $validation);
$guide = $spreadsheet->createSheet();
$guide->setTitle('Instructions');
$guide->fromArray([
['Item', 'Rule'],
['Effect', 'The complete recommendation set for each source_sku + website row is replaced.'],
['source_sku', 'SKU of the product whose recommendation area is being configured.'],
['website', 'default, us, au, eu, or uk. Website rows override default.'],
['recommended_sku_1 ... recommended_sku_20', 'Enter one recommended SKU per cell. Products display from left to right.'],
['One row per scope', 'Put all recommendations for the same source_sku + website on the same row.'],
['Empty set', 'Leave every recommended_sku cell blank to explicitly show no recommendations for that scope.'],
['Manual changes', 'Use the product edit page for partial additions, removals, or restoring website inheritance.'],
], null, 'A1');
$guide->getStyle('A1:B1')->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '17365D']],
]);
$guide->getColumnDimension('A')->setWidth(24);
$guide->getColumnDimension('B')->setWidth(100);
$guide->getStyle('A1:B8')->getAlignment()->setWrapText(true);
$guide->getStyle('A1:B8')->applyFromArray([
'borders' => ['allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => 'B7C9D6'],
]],
]);
$guide->setShowGridlines(false);
$example = $spreadsheet->createSheet();
$example->setTitle('Example');
$exampleRows = [
$headers,
array_pad(['PLA-001', 'default', 'ACC-001', 'ACC-002', 'ACC-003'], count($headers), null),
array_pad(['PLA-002', 'uk', 'ACC-004', 'ACC-005'], count($headers), null),
];
$example->fromArray($exampleRows, null, 'A1');
$example->getStyle('A1:' . $lastColumn . '1')->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '17365D']],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
]);
$example->getColumnDimension('A')->setWidth(28);
$example->getColumnDimension('B')->setWidth(18);
for ($column = 3; $column <= count($headers); $column++) {
$example->getColumnDimensionByColumn($column)->setWidth(24);
}
$example->getStyle('A1:' . $lastColumn . count($exampleRows))->applyFromArray([
'borders' => ['allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['rgb' => 'B7C9D6'],
]],
]);
$example->setShowGridlines(false);
$spreadsheet->setActiveSheetIndex(0);
$temporary = fopen('php://temp', 'w+b');
(new Xlsx($spreadsheet))->save($temporary);
rewind($temporary);
$contents = stream_get_contents($temporary);
fclose($temporary);
$spreadsheet->disconnectWorksheets();
return (string)$contents;
}
private function getHeaders(): array
{
$headers = ['source_sku', 'website'];
for ($position = 1; $position <= SpreadsheetReader::MAX_RECOMMENDATIONS; $position++) {
$headers[] = 'recommended_sku_' . $position;
}
return $headers;
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ProductRecommendation;
use Magento\Backend\Model\Session;
class ValidationState
{
private const KEY = 'esun_product_recommendation_import';
public function __construct(private readonly Session $session)
{
}
public function save(string $path, array $result): void
{
$this->session->setData(self::KEY, [
'path' => $path,
'valid' => (bool)$result['valid'],
'stats' => $result['stats'],
'errors' => $result['errors'],
'preview' => array_slice((array)$result['preview'], 0, 100),
'preview_truncated' => count((array)$result['preview']) > 100,
]);
}
public function get(): array
{
return (array)$this->session->getData(self::KEY);
}
public function clear(): void
{
$this->session->unsetData(self::KEY);
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ProductRecommendation;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
class WebsiteResolver
{
private const WEBSITE_CODE_MAP = [
'us' => 'us_site',
'au' => 'au',
'eu' => 'eu',
'uk' => 'uk',
];
private array $resolved = [];
public function __construct(private readonly StoreManagerInterface $storeManager)
{
}
public function resolve(string $alias): array
{
$alias = trim($alias);
if ($alias === 'default') {
return ['alias' => 'default', 'code' => 'admin', 'website_id' => 0, 'store_ids' => []];
}
if ($alias !== strtolower($alias) || !isset(self::WEBSITE_CODE_MAP[$alias])) {
throw new LocalizedException(__('Website must be one of: default, us, au, eu, uk.'));
}
if (isset($this->resolved[$alias])) {
return $this->resolved[$alias];
}
try {
$website = $this->storeManager->getWebsite(self::WEBSITE_CODE_MAP[$alias]);
} catch (\Throwable) {
throw new LocalizedException(__('Magento website for "%1" is not configured.', $alias));
}
return $this->resolved[$alias] = [
'alias' => $alias,
'code' => (string)$website->getCode(),
'website_id' => (int)$website->getId(),
'store_ids' => array_values(array_map('intval', $website->getStoreIds())),
];
}
public function aliases(): array
{
return ['default', ...array_keys(self::WEBSITE_CODE_MAP)];
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ProductRecommendation;
use Magento\Framework\App\Cache\TypeListInterface;
class Writer
{
public function __construct(
private readonly RecommendationRepository $repository,
private readonly TypeListInterface $cacheTypeList
) {
}
public function replaceGroups(array $groups): array
{
$recommendations = 0;
foreach ($groups as $group) {
$productIds = array_values(array_map('intval', (array)$group['product_ids']));
$recommendations += count($productIds);
}
$this->repository->replaceGroups($groups);
if ($groups !== []) {
$this->invalidateCache();
}
return ['groups' => count($groups), 'recommendations' => $recommendations];
}
public function invalidateCache(): void
{
$this->cacheTypeList->cleanType('block_html');
$this->cacheTypeList->cleanType('full_page');
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class CertificationType extends AbstractDb
{
protected function _construct(): void
{
$this->_init('esun_catalog_certification_type', 'type_id');
}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Esun\Catalog\Model\ResourceModel\CertificationType;
use Esun\Catalog\Model\CertificationType;
use Esun\Catalog\Model\ResourceModel\CertificationType as CertificationTypeResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct(): void
{
$this->_init(CertificationType::class, CertificationTypeResource::class);
}
}

Some files were not shown because too many files have changed in this diff Show More