init
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class ColorOption extends AbstractDb
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_catalog_color_option', 'entity_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\ResourceModel\ColorOption;
|
||||
|
||||
use Esun\Catalog\Model\ColorOption;
|
||||
use Esun\Catalog\Model\ResourceModel\ColorOption as ColorOptionResource;
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(ColorOption::class, ColorOptionResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class Faq extends AbstractDb
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_catalog_faq', 'faq_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\ResourceModel\Faq;
|
||||
|
||||
use Esun\Catalog\Model\Faq;
|
||||
use Esun\Catalog\Model\ResourceModel\Faq as FaqResource;
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(Faq::class, FaqResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class SpecificationBrand extends AbstractDb
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_catalog_specification_brand', 'brand_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\ResourceModel\SpecificationBrand;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationBrand as SpecificationBrandResource;
|
||||
use Esun\Catalog\Model\SpecificationBrand;
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(SpecificationBrand::class, SpecificationBrandResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class SpecificationFile extends AbstractDb
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_catalog_specification_file', 'file_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\ResourceModel\SpecificationFile;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationFile as SpecificationFileResource;
|
||||
use Esun\Catalog\Model\SpecificationFile;
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(SpecificationFile::class, SpecificationFileResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class SpecificationImport extends AbstractDb
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_catalog_specification_import', 'import_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\ResourceModel\SpecificationImport;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationImport as SpecificationImportResource;
|
||||
use Esun\Catalog\Model\SpecificationImport;
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected function _initSelect(): void
|
||||
{
|
||||
parent::_initSelect();
|
||||
$this->getSelect()->joinLeft(
|
||||
['brand' => $this->getTable('esun_catalog_specification_brand')],
|
||||
'main_table.brand_id = brand.brand_id',
|
||||
['brand_name' => 'brand.brand_name']
|
||||
);
|
||||
$this->addFilterToMap('import_id', 'main_table.import_id');
|
||||
$this->addFilterToMap('brand_id', 'main_table.brand_id');
|
||||
$this->addFilterToMap('archive_file', 'main_table.archive_file');
|
||||
$this->addFilterToMap('file_count', 'main_table.file_count');
|
||||
$this->addFilterToMap('status', 'main_table.status');
|
||||
$this->addFilterToMap('updated_at', 'main_table.updated_at');
|
||||
}
|
||||
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(SpecificationImport::class, SpecificationImportResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class BooleanOptions implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
return [
|
||||
['value' => '1', 'label' => __('Yes')],
|
||||
['value' => '0', 'label' => __('No')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model\Source;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationBrand\CollectionFactory;
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class SpecificationBrandOptions implements OptionSourceInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CollectionFactory $collectionFactory
|
||||
) {
|
||||
}
|
||||
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
$options = [['value' => '', 'label' => __('Select a brand')]];
|
||||
$collection = $this->collectionFactory->create()
|
||||
->addFieldToFilter('status', 1)
|
||||
->setOrder('sort_order', 'ASC')
|
||||
->setOrder('brand_name', 'ASC');
|
||||
|
||||
foreach ($collection as $brand) {
|
||||
$options[] = [
|
||||
'value' => (string)$brand->getId(),
|
||||
'label' => (string)$brand->getData('brand_name'),
|
||||
];
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationFile\CollectionFactory as FileCollectionFactory;
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationImport as SpecificationImportResource;
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationImport\CollectionFactory as ImportCollectionFactory;
|
||||
use Magento\Framework\App\Filesystem\DirectoryList;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Filesystem;
|
||||
|
||||
class SpecificationArchiveRebuilder
|
||||
{
|
||||
public function __construct(
|
||||
private readonly FileCollectionFactory $fileCollectionFactory,
|
||||
private readonly ImportCollectionFactory $importCollectionFactory,
|
||||
private readonly SpecificationImportFactory $importFactory,
|
||||
private readonly SpecificationImportResource $importResource,
|
||||
private readonly SpecificationMedia $media,
|
||||
private readonly Filesystem $filesystem
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{status:string,path:string,file_count:int,missing_count:int}
|
||||
*/
|
||||
public function rebuild(SpecificationBrand $brand, bool $force = false): array
|
||||
{
|
||||
if (!class_exists(\ZipArchive::class)) {
|
||||
throw new LocalizedException(__('Archive rebuilding requires the PHP ZipArchive extension.'));
|
||||
}
|
||||
|
||||
$brandId = (int)$brand->getId();
|
||||
if ($brandId <= 0) {
|
||||
throw new LocalizedException(__('The specification brand must be saved before rebuilding its archive.'));
|
||||
}
|
||||
|
||||
$import = $this->getLatestImport($brandId);
|
||||
$currentPath = $import ? (string)$import->getData('archive_file') : '';
|
||||
if (!$force && $currentPath !== '' && $this->media->exists($currentPath)) {
|
||||
return [
|
||||
'status' => 'skipped',
|
||||
'path' => $currentPath,
|
||||
'file_count' => (int)$import->getData('file_count'),
|
||||
'missing_count' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
$brandDirectoryName = $this->sanitizeArchiveSegment((string)$brand->getData('brand_name'), 'brand-' . $brandId);
|
||||
$archiveDirectory = SpecificationMedia::ARCHIVE_PATH . '/' . $brandId;
|
||||
$archivePath = $archiveDirectory . '/' . $brandDirectoryName . '.zip';
|
||||
|
||||
if (!$force && $this->media->exists($archivePath)) {
|
||||
$fileCount = (int)$this->fileCollectionFactory->create()
|
||||
->addFieldToFilter('brand_id', $brandId)
|
||||
->getSize();
|
||||
$this->saveImport($import, $brandId, $archivePath, $fileCount);
|
||||
|
||||
return [
|
||||
'status' => 'linked',
|
||||
'path' => $archivePath,
|
||||
'file_count' => $fileCount,
|
||||
'missing_count' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
$mediaDirectory->create($archiveDirectory);
|
||||
$temporaryPath = $archiveDirectory . '/.rebuild-' . bin2hex(random_bytes(8)) . '.zip';
|
||||
$zip = new \ZipArchive();
|
||||
if ($zip->open($mediaDirectory->getAbsolutePath($temporaryPath), \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
|
||||
throw new LocalizedException(__('Unable to create the specification archive for brand "%1".', $brand->getData('brand_name')));
|
||||
}
|
||||
|
||||
$fileCount = 0;
|
||||
$missingCount = 0;
|
||||
$entryNames = [];
|
||||
try {
|
||||
try {
|
||||
$collection = $this->fileCollectionFactory->create()
|
||||
->addFieldToFilter('brand_id', $brandId)
|
||||
->setOrder('model_name', 'ASC')
|
||||
->setOrder('file_name', 'ASC');
|
||||
|
||||
foreach ($collection as $file) {
|
||||
$filePath = (string)$file->getData('file_path');
|
||||
if ($filePath === '' || !$this->media->exists($filePath)) {
|
||||
$missingCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$modelName = $this->sanitizeArchiveSegment((string)$file->getData('model_name'), 'model');
|
||||
$fileName = $this->sanitizeArchiveSegment((string)$file->getData('file_name'), 'specification');
|
||||
$entryName = $brandDirectoryName . '/' . $modelName . '/' . $fileName;
|
||||
if (isset($entryNames[$entryName])) {
|
||||
$entryName = $brandDirectoryName . '/' . $modelName . '/'
|
||||
. pathinfo($fileName, PATHINFO_FILENAME) . '-' . (int)$file->getId()
|
||||
. ($this->getExtension($fileName) !== '' ? '.' . $this->getExtension($fileName) : '');
|
||||
}
|
||||
|
||||
if ($zip->addFile($this->media->getAbsolutePath($filePath), $entryName)) {
|
||||
$entryNames[$entryName] = true;
|
||||
$fileCount++;
|
||||
} else {
|
||||
$missingCount++;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$closed = $zip->close();
|
||||
}
|
||||
} catch (\Throwable $exception) {
|
||||
if ($mediaDirectory->isExist($temporaryPath)) {
|
||||
$mediaDirectory->delete($temporaryPath);
|
||||
}
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
if (!$closed || $fileCount === 0) {
|
||||
if ($mediaDirectory->isExist($temporaryPath)) {
|
||||
$mediaDirectory->delete($temporaryPath);
|
||||
}
|
||||
throw new LocalizedException(
|
||||
__('No readable specification files were available for brand "%1".', $brand->getData('brand_name'))
|
||||
);
|
||||
}
|
||||
|
||||
if ($mediaDirectory->isExist($archivePath)) {
|
||||
$mediaDirectory->delete($archivePath);
|
||||
}
|
||||
$mediaDirectory->renameFile($temporaryPath, $archivePath);
|
||||
|
||||
if ($currentPath !== '' && $currentPath !== $archivePath) {
|
||||
$this->media->delete($currentPath);
|
||||
}
|
||||
$this->saveImport($import, $brandId, $archivePath, $fileCount);
|
||||
|
||||
return [
|
||||
'status' => 'rebuilt',
|
||||
'path' => $archivePath,
|
||||
'file_count' => $fileCount,
|
||||
'missing_count' => $missingCount,
|
||||
];
|
||||
}
|
||||
|
||||
private function getLatestImport(int $brandId): ?SpecificationImport
|
||||
{
|
||||
$import = $this->importCollectionFactory->create()
|
||||
->addFieldToFilter('brand_id', $brandId)
|
||||
->setOrder('updated_at', 'DESC')
|
||||
->setPageSize(1)
|
||||
->getFirstItem();
|
||||
|
||||
return $import->getId() ? $import : null;
|
||||
}
|
||||
|
||||
private function saveImport(
|
||||
?SpecificationImport $import,
|
||||
int $brandId,
|
||||
string $archivePath,
|
||||
int $fileCount
|
||||
): void {
|
||||
$import ??= $this->importFactory->create();
|
||||
$import->setData('brand_id', $brandId);
|
||||
$import->setData('archive_file', $archivePath);
|
||||
$import->setData('file_count', $fileCount);
|
||||
$import->setData('status', 1);
|
||||
$this->importResource->save($import);
|
||||
}
|
||||
|
||||
private function sanitizeArchiveSegment(string $value, string $fallback): string
|
||||
{
|
||||
$value = trim(str_replace(['/', '\\'], '_', $value));
|
||||
$value = preg_replace('/[\x00-\x1F\x7F]+/u', '_', $value) ?: '';
|
||||
$value = trim($value, " .\t\n\r\0\x0B");
|
||||
|
||||
return $value !== '' ? $value : $fallback;
|
||||
}
|
||||
|
||||
private function getExtension(string $fileName): string
|
||||
{
|
||||
return (string)pathinfo($fileName, PATHINFO_EXTENSION);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model;
|
||||
|
||||
use Magento\Framework\Model\AbstractModel;
|
||||
|
||||
class SpecificationBrand extends AbstractModel
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(ResourceModel\SpecificationBrand::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model;
|
||||
|
||||
use Magento\Framework\Model\AbstractModel;
|
||||
|
||||
class SpecificationFile extends AbstractModel
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(ResourceModel\SpecificationFile::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model;
|
||||
|
||||
use Magento\Framework\Model\AbstractModel;
|
||||
|
||||
class SpecificationImport extends AbstractModel
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(ResourceModel\SpecificationImport::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model;
|
||||
|
||||
use Magento\Framework\App\Filesystem\DirectoryList;
|
||||
use Magento\Framework\App\Request\Http;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Filesystem;
|
||||
use Magento\MediaStorage\Model\File\UploaderFactory;
|
||||
|
||||
class SpecificationMedia
|
||||
{
|
||||
public const LOGO_PATH = 'esun/catalog/specifications/brand-logo';
|
||||
public const ARCHIVE_PATH = 'esun/catalog/specifications/archive';
|
||||
public const FILE_PATH = 'esun/catalog/specifications/file';
|
||||
|
||||
public function __construct(
|
||||
private readonly UploaderFactory $uploaderFactory,
|
||||
private readonly Filesystem $filesystem,
|
||||
private readonly Http $request
|
||||
) {
|
||||
}
|
||||
|
||||
public function saveLogo(string $field): ?string
|
||||
{
|
||||
return $this->saveUpload($field, self::LOGO_PATH, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']);
|
||||
}
|
||||
|
||||
public function saveArchive(string $field, int $brandId): ?string
|
||||
{
|
||||
return $this->saveUpload($field, self::ARCHIVE_PATH . '/' . $brandId, ['zip']);
|
||||
}
|
||||
|
||||
public function hasUpload(string $field): bool
|
||||
{
|
||||
$file = $this->request->getFiles($field);
|
||||
|
||||
return is_array($file)
|
||||
&& !empty($file['tmp_name'])
|
||||
&& (int)($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE;
|
||||
}
|
||||
|
||||
public function writeSpecificationFile(int $brandId, string $modelName, string $fileName, string $contents): string
|
||||
{
|
||||
$relativeDirectory = self::FILE_PATH . '/' . $brandId . '/' . $this->sanitizePathSegment($modelName);
|
||||
$relativePath = $relativeDirectory . '/' . $this->sanitizeFilename($fileName);
|
||||
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
$media->create($relativeDirectory);
|
||||
$media->writeFile($relativePath, $contents);
|
||||
|
||||
return $relativePath;
|
||||
}
|
||||
|
||||
public function deleteBrandFiles(int $brandId): void
|
||||
{
|
||||
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
foreach ([self::ARCHIVE_PATH . '/' . $brandId, self::FILE_PATH . '/' . $brandId] as $path) {
|
||||
if ($media->isExist($path)) {
|
||||
$media->delete($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteBrandParsedFiles(int $brandId): void
|
||||
{
|
||||
$path = self::FILE_PATH . '/' . $brandId;
|
||||
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
if ($media->isExist($path)) {
|
||||
$media->delete($path);
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteBrandArchiveFiles(int $brandId): void
|
||||
{
|
||||
$path = self::ARCHIVE_PATH . '/' . $brandId;
|
||||
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
if ($media->isExist($path)) {
|
||||
$media->delete($path);
|
||||
}
|
||||
}
|
||||
|
||||
public function delete(string $path): void
|
||||
{
|
||||
$path = ltrim($path, '/');
|
||||
if ($path === '' || !str_starts_with($path, 'esun/catalog/specifications/')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
if ($media->isExist($path)) {
|
||||
$media->delete($path);
|
||||
}
|
||||
}
|
||||
|
||||
public function getAbsolutePath(string $path): string
|
||||
{
|
||||
return $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath(ltrim($path, '/'));
|
||||
}
|
||||
|
||||
public function exists(string $path): bool
|
||||
{
|
||||
$path = ltrim($path, '/');
|
||||
|
||||
return $path !== ''
|
||||
&& $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->isExist($path);
|
||||
}
|
||||
|
||||
public function getFileSize(string $path): int
|
||||
{
|
||||
$path = ltrim($path, '/');
|
||||
if ($path === '' || !$this->exists($path)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$stat = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->stat($path);
|
||||
|
||||
return is_array($stat) ? (int)($stat['size'] ?? 0) : 0;
|
||||
}
|
||||
|
||||
public function sanitizePathSegment(string $value): string
|
||||
{
|
||||
$value = trim($value);
|
||||
$value = preg_replace('/[^A-Za-z0-9._-]+/', '_', $value) ?: '';
|
||||
$value = trim($value, '._-');
|
||||
|
||||
return $value !== '' ? $value : 'model';
|
||||
}
|
||||
|
||||
private function saveUpload(string $field, string $relativeDirectory, array $extensions): ?string
|
||||
{
|
||||
$file = $this->request->getFiles($field);
|
||||
if (!is_array($file)
|
||||
|| empty($file['tmp_name'])
|
||||
|| (int)($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if ((int)($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
|
||||
throw new LocalizedException(__('The %1 file could not be uploaded.', $field));
|
||||
}
|
||||
|
||||
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
$media->create($relativeDirectory);
|
||||
$uploader = $this->uploaderFactory->create(['fileId' => $field]);
|
||||
$uploader->setAllowedExtensions($extensions);
|
||||
$uploader->setAllowRenameFiles(true);
|
||||
$uploader->setFilesDispersion(false);
|
||||
$saved = $uploader->save($media->getAbsolutePath($relativeDirectory));
|
||||
if (!is_array($saved) || empty($saved['file'])) {
|
||||
throw new LocalizedException(__('Unable to save the %1 file.', $field));
|
||||
}
|
||||
|
||||
return trim($relativeDirectory . '/' . ltrim((string)$saved['file'], '/'), '/');
|
||||
}
|
||||
|
||||
private function sanitizeFilename(string $value): string
|
||||
{
|
||||
$value = strtolower(trim($value));
|
||||
$value = preg_replace('/[^a-z0-9._+ -]+/', '_', $value) ?: '';
|
||||
$value = preg_replace('/\\s+/', ' ', $value) ?: '';
|
||||
$value = trim($value, ' ._-');
|
||||
|
||||
return $value !== '' ? $value : 'specification';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Catalog\Model;
|
||||
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationFile as SpecificationFileResource;
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationFile\CollectionFactory as SpecificationFileCollectionFactory;
|
||||
use Esun\Catalog\Model\ResourceModel\SpecificationImport\CollectionFactory as SpecificationImportCollectionFactory;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
|
||||
class SpecificationZipImporter
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SpecificationMedia $media,
|
||||
private readonly SpecificationImportCollectionFactory $importCollectionFactory,
|
||||
private readonly SpecificationFileCollectionFactory $fileCollectionFactory,
|
||||
private readonly SpecificationImportFactory $importFactory,
|
||||
private readonly SpecificationFileFactory $fileFactory,
|
||||
private readonly SpecificationFileResource $fileResource
|
||||
) {
|
||||
}
|
||||
|
||||
public function import(SpecificationBrand $brand, string $archivePath): SpecificationImport
|
||||
{
|
||||
if (!class_exists(\ZipArchive::class)) {
|
||||
throw new LocalizedException(__('ZIP import requires the PHP ZipArchive extension.'));
|
||||
}
|
||||
|
||||
$brandId = (int)$brand->getId();
|
||||
if ($brandId <= 0) {
|
||||
throw new LocalizedException(__('Please save the brand before importing specifications.'));
|
||||
}
|
||||
|
||||
$zip = new \ZipArchive();
|
||||
$absoluteArchivePath = $this->media->getAbsolutePath($archivePath);
|
||||
if ($zip->open($absoluteArchivePath) !== true) {
|
||||
throw new LocalizedException(__('Unable to open the ZIP file.'));
|
||||
}
|
||||
|
||||
$this->deleteExistingBrandData($brandId);
|
||||
|
||||
$import = $this->importFactory->create();
|
||||
$import->setData([
|
||||
'brand_id' => $brandId,
|
||||
'archive_file' => $archivePath,
|
||||
'file_count' => 0,
|
||||
'status' => 1,
|
||||
])->save();
|
||||
|
||||
$brandName = (string)$brand->getData('brand_name');
|
||||
$normalizedBrandName = $this->normalizeName($brandName);
|
||||
$fileCount = 0;
|
||||
|
||||
for ($index = 0; $index < $zip->numFiles; $index++) {
|
||||
$stat = $zip->statIndex($index);
|
||||
$entryName = (string)($stat['name'] ?? '');
|
||||
if ($this->shouldSkipEntry($entryName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parts = array_values(array_filter(explode('/', trim($entryName, '/')), static fn (string $part): bool => $part !== ''));
|
||||
if (count($parts) < 3) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fileName = array_pop($parts);
|
||||
$modelName = (string)array_pop($parts);
|
||||
$entryBrandName = (string)array_pop($parts);
|
||||
if ($this->normalizeName($entryBrandName) !== $normalizedBrandName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$contents = $zip->getFromIndex($index);
|
||||
if ($contents === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$lowerFileName = strtolower($fileName);
|
||||
$relativePath = $this->media->writeSpecificationFile($brandId, $modelName, $lowerFileName, $contents);
|
||||
$file = $this->fileFactory->create();
|
||||
$file->setData([
|
||||
'import_id' => (int)$import->getId(),
|
||||
'brand_id' => $brandId,
|
||||
'brand_name' => $brandName,
|
||||
'brand_logo' => (string)$brand->getData('brand_logo'),
|
||||
'model_name' => $modelName,
|
||||
'file_name' => $lowerFileName,
|
||||
'file_path' => $relativePath,
|
||||
'product_name_key' => $this->buildProductNameKey($lowerFileName),
|
||||
'is_product_specific' => (int)$brand->getData('is_product_specific') === 1 ? 1 : 0,
|
||||
'file_size' => strlen($contents),
|
||||
'file_mtime' => !empty($stat['mtime']) ? date('Y-m-d H:i:s', (int)$stat['mtime']) : null,
|
||||
]);
|
||||
$this->fileResource->save($file);
|
||||
$fileCount++;
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
|
||||
$import->setData('file_count', $fileCount)->save();
|
||||
if ($fileCount === 0) {
|
||||
$import->delete();
|
||||
$this->media->deleteBrandParsedFiles($brandId);
|
||||
throw new LocalizedException(__('No specification files were found for brand "%1" in this ZIP file.', $brandName));
|
||||
}
|
||||
|
||||
return $import;
|
||||
}
|
||||
|
||||
public function buildProductNameKey(string $fileName): string
|
||||
{
|
||||
$withoutExtension = pathinfo(strtolower($fileName), PATHINFO_FILENAME);
|
||||
$key = preg_replace('/[^a-z0-9]+/', ' ', $withoutExtension) ?: '';
|
||||
$key = preg_replace('/\\s+/', ' ', $key) ?: '';
|
||||
|
||||
return trim($key);
|
||||
}
|
||||
|
||||
public function buildProductSearchTokens(string $productName): array
|
||||
{
|
||||
$normalized = $this->buildProductNameKey($productName);
|
||||
$tokens = [];
|
||||
if ($normalized !== '') {
|
||||
$tokens[$normalized] = $normalized;
|
||||
$parts = preg_split('/\\s+/', $normalized) ?: [];
|
||||
for ($length = count($parts); $length >= 1; $length--) {
|
||||
for ($start = 0; $start <= count($parts) - $length; $start++) {
|
||||
$token = implode(' ', array_slice($parts, $start, $length));
|
||||
if (strlen($token) >= 3) {
|
||||
$tokens[$token] = $token;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($tokens);
|
||||
}
|
||||
|
||||
private function deleteExistingBrandData(int $brandId): void
|
||||
{
|
||||
foreach ($this->importCollectionFactory->create()->addFieldToFilter('brand_id', $brandId) as $import) {
|
||||
$import->delete();
|
||||
}
|
||||
foreach ($this->fileCollectionFactory->create()->addFieldToFilter('brand_id', $brandId) as $file) {
|
||||
$file->delete();
|
||||
}
|
||||
$this->media->deleteBrandParsedFiles($brandId);
|
||||
}
|
||||
|
||||
private function shouldSkipEntry(string $entryName): bool
|
||||
{
|
||||
$entryName = trim($entryName);
|
||||
if ($entryName === '' || str_ends_with($entryName, '/')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$parts = explode('/', $entryName);
|
||||
$basename = end($parts);
|
||||
|
||||
return str_contains($entryName, '__MACOSX/')
|
||||
|| $basename === '.DS_Store'
|
||||
|| str_starts_with((string)$basename, '._');
|
||||
}
|
||||
|
||||
private function normalizeName(string $value): string
|
||||
{
|
||||
$value = strtolower(trim($value));
|
||||
$value = preg_replace('/[^a-z0-9]+/', '', $value) ?: '';
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user