This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
+174
View File
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
namespace Esun\FreeGift\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Store\Model\ScopeInterface;
class Config
{
private const XML_PATH_ENABLED = 'esun_free_gift/general/enabled';
private const XML_PATH_GIFT_SKU = 'esun_free_gift/general/gift_sku';
private const XML_PATH_START_DATE = 'esun_free_gift/general/start_date';
private const XML_PATH_END_DATE = 'esun_free_gift/general/end_date';
private const XML_PATH_TIER_ITEMS = 'esun_free_gift/tiers/items';
private const XML_PATH_TIER_AMOUNT = 'esun_free_gift/tiers/tier_%d_amount';
private const XML_PATH_TIER_QTY = 'esun_free_gift/tiers/tier_%d_qty';
public function __construct(
private readonly ScopeConfigInterface $scopeConfig,
private readonly TimezoneInterface $timezone,
private readonly Json $serializer
) {
}
public function isEnabled(?int $storeId = null): bool
{
return $this->scopeConfig->isSetFlag(
self::XML_PATH_ENABLED,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
public function getGiftSku(?int $storeId = null): string
{
return trim((string)$this->scopeConfig->getValue(
self::XML_PATH_GIFT_SKU,
ScopeInterface::SCOPE_STORE,
$storeId
));
}
public function isGiftSku(string $sku, ?int $storeId = null): bool
{
$giftSku = $this->getGiftSku($storeId);
return $giftSku !== '' && strcasecmp($giftSku, trim($sku)) === 0;
}
public function isActive(?int $storeId = null): bool
{
if (!$this->isEnabled($storeId) || $this->getGiftSku($storeId) === '') {
return false;
}
$today = $this->timezone->scopeDate($storeId)->format('Y-m-d');
$startDate = $this->normalizeDate($this->getValue(self::XML_PATH_START_DATE, $storeId));
$endDate = $this->normalizeDate($this->getValue(self::XML_PATH_END_DATE, $storeId));
return ($startDate === '' || $today >= $startDate)
&& ($endDate === '' || $today <= $endDate);
}
public function getTargetQuantity(float $eligibleBaseSubtotal, ?int $storeId = null): int
{
if (!$this->isActive($storeId)) {
return 0;
}
$targetQuantity = 0;
$subtotal = round(max(0.0, $eligibleBaseSubtotal), 2);
foreach ($this->getTiers($storeId) as $tier) {
if ($subtotal + 0.0001 >= $tier['amount']) {
$targetQuantity = $tier['qty'];
}
}
return $targetQuantity;
}
/** @return array<int, array{amount: float, qty: int}> */
public function getTiers(?int $storeId = null): array
{
$configuredTiers = $this->getConfiguredTiers($storeId);
if ($configuredTiers !== []) {
return $configuredTiers;
}
$tiers = [];
for ($index = 1; $index <= 3; $index++) {
$amount = max(0.0, (float)$this->getValue(sprintf(self::XML_PATH_TIER_AMOUNT, $index), $storeId));
$quantity = max(0, (int)$this->getValue(sprintf(self::XML_PATH_TIER_QTY, $index), $storeId));
if ($quantity > 0) {
$tiers[] = ['amount' => $amount, 'qty' => $quantity];
}
}
usort(
$tiers,
static fn (array $left, array $right): int => $left['amount'] <=> $right['amount']
);
return $tiers;
}
/** @return array<int, array{amount: float, qty: int}> */
private function getConfiguredTiers(?int $storeId): array
{
$value = $this->scopeConfig->getValue(
self::XML_PATH_TIER_ITEMS,
ScopeInterface::SCOPE_STORE,
$storeId
);
try {
$items = is_array($value)
? $value
: (trim((string)$value) === '' ? [] : $this->serializer->unserialize((string)$value));
} catch (\InvalidArgumentException) {
return [];
}
if (!is_array($items)) {
return [];
}
$tiers = [];
foreach ($items as $item) {
if (!is_array($item)) {
continue;
}
$quantity = max(0, (int)($item['qty'] ?? 0));
if ($quantity <= 0) {
continue;
}
$tiers[] = [
'amount' => max(0.0, (float)($item['amount'] ?? 0)),
'qty' => $quantity,
];
}
usort($tiers, static fn (array $left, array $right): int => $left['amount'] <=> $right['amount']);
return $tiers;
}
private function getValue(string $path, ?int $storeId = null): string
{
return trim((string)$this->scopeConfig->getValue(
$path,
ScopeInterface::SCOPE_STORE,
$storeId
));
}
private function normalizeDate(string $value): string
{
if ($value === '') {
return '';
}
$timestamp = strtotime($value);
return $timestamp === false ? '' : date('Y-m-d', $timestamp);
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\FreeGift\Model\Config\Backend;
use Magento\Config\Model\Config\Backend\Serialized\ArraySerialized;
use Magento\Config\Model\ResourceModel\Config\Data as ConfigResource;
use Magento\Config\Model\ResourceModel\Config\Data\Collection as ConfigCollection;
class TierItems extends ArraySerialized
{
protected function _construct(): void
{
$this->_setResourceModel(ConfigResource::class, ConfigCollection::class);
}
public function beforeSave()
{
$items = [];
$value = $this->getValue();
if (is_array($value)) {
unset($value['__empty']);
foreach ($value as $row) {
if (!is_array($row)) {
continue;
}
$amount = max(0.0, (float)($row['amount'] ?? 0));
$quantity = max(0, (int)($row['qty'] ?? 0));
if ($quantity <= 0) {
continue;
}
$items[] = ['amount' => $amount, 'qty' => $quantity];
}
}
usort($items, static fn (array $left, array $right): int => $left['amount'] <=> $right['amount']);
$this->setValue($items);
return parent::beforeSave();
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Esun\FreeGift\Model;
final class GiftItem
{
public const FLAG = 'is_esun_free_gift';
public const OPTION_CODE = 'esun_free_gift';
public const TOTALS_GUARD = 'esun_free_gift_totals_syncing';
}
@@ -0,0 +1,165 @@
<?php
declare(strict_types=1);
namespace Esun\FreeGift\Model;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Type;
use Magento\Framework\DataObjectFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\Quote\Item;
use Psr\Log\LoggerInterface;
class GiftSynchronizer
{
public function __construct(
private readonly Config $config,
private readonly ProductRepositoryInterface $productRepository,
private readonly DataObjectFactory $dataObjectFactory,
private readonly Json $json,
private readonly InternalAddGuard $internalAddGuard,
private readonly LoggerInterface $logger
) {
}
public function synchronize(Quote $quote, float $eligibleBaseSubtotal): bool
{
$storeId = (int)$quote->getStoreId();
if ($storeId <= 0) {
return false;
}
$targetQuantity = $this->config->getTargetQuantity($eligibleBaseSubtotal, $storeId);
$giftItems = $this->getGiftItems($quote);
if ($targetQuantity <= 0) {
return $this->removeGiftItems($quote, $giftItems);
}
$changed = false;
$configuredGiftItems = [];
foreach ($giftItems as $giftItem) {
if ($this->config->isGiftSku((string)$giftItem->getSku(), $storeId)) {
$configuredGiftItems[] = $giftItem;
continue;
}
$quote->deleteItem($giftItem);
$changed = true;
}
if (!$configuredGiftItems) {
return $this->addGiftItem($quote, $targetQuantity, $storeId) || $changed;
}
$primaryItem = array_shift($configuredGiftItems);
if ($primaryItem instanceof Item) {
$changed = $this->prepareGiftItem($primaryItem, $targetQuantity) || $changed;
}
foreach ($configuredGiftItems as $duplicateItem) {
$quote->deleteItem($duplicateItem);
$changed = true;
}
return $changed;
}
/** @return Item[] */
private function getGiftItems(Quote $quote): array
{
$items = [];
foreach ($quote->getAllVisibleItems() as $item) {
if ((bool)$item->getData(GiftItem::FLAG)) {
$items[] = $item;
}
}
return $items;
}
/** @param Item[] $giftItems */
private function removeGiftItems(Quote $quote, array $giftItems): bool
{
foreach ($giftItems as $giftItem) {
$quote->deleteItem($giftItem);
}
return $giftItems !== [];
}
private function addGiftItem(Quote $quote, int $quantity, int $storeId): bool
{
$sku = $this->config->getGiftSku($storeId);
try {
$product = clone $this->productRepository->get($sku, false, $storeId, true);
if ($product->getTypeId() !== Type::TYPE_SIMPLE) {
throw new LocalizedException(__('The configured free gift must be a simple product.'));
}
$product->setStoreId($storeId);
$product->setIsSuperMode(true);
$product->addCustomOption(GiftItem::OPTION_CODE, '1');
$product->addCustomOption(
'additional_options',
$this->json->serialize([
[
'label' => (string)__('Promotion'),
'value' => (string)__('Free Gift')
]
])
);
$request = $this->dataObjectFactory->create(['data' => ['qty' => $quantity]]);
$result = $this->internalAddGuard->execute(
static fn () => $quote->addProduct($product, $request)
);
if (!$result instanceof Item) {
throw new LocalizedException(__(is_string($result) ? $result : 'The free gift could not be added.'));
}
$this->prepareGiftItem($result, $quantity);
return true;
} catch (\Throwable $exception) {
$this->logger->error(
'Unable to add the configured automatic free gift.',
[
'sku' => $sku,
'store_id' => $storeId,
'exception' => $exception
]
);
return false;
}
}
private function prepareGiftItem(Item $item, int $quantity): bool
{
$changed = abs((float)$item->getQty() - $quantity) > 0.0001
|| !(bool)$item->getData(GiftItem::FLAG)
|| $item->getCustomPrice() === null
|| abs((float)$item->getCustomPrice()) > 0.0001;
$item->setQty($quantity);
$item->setData(GiftItem::FLAG, 1);
$item->setCustomPrice(0.0);
$item->setOriginalCustomPrice(0.0);
$item->setOriginalPrice(0.0);
$item->setBaseOriginalPrice(0.0);
$item->setNoDiscount(1);
$item->setDiscountAmount(0.0);
$item->setBaseDiscountAmount(0.0);
$item->setAppliedRuleIds(null);
$item->getProduct()->setIsSuperMode(true);
return $changed;
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Esun\FreeGift\Model;
class InternalAddGuard
{
private int $depth = 0;
public function isAllowed(): bool
{
return $this->depth > 0;
}
public function execute(callable $callback): mixed
{
$this->depth++;
try {
return $callback();
} finally {
$this->depth--;
}
}
}