init
This commit is contained in:
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user