init
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FreeGift\Block\Adminhtml\System\Config\Form\Field;
|
||||
|
||||
use Magento\Config\Block\System\Config\Form\Field;
|
||||
use Magento\Framework\Data\Form\Element\AbstractElement;
|
||||
|
||||
class Date extends Field
|
||||
{
|
||||
protected function _getElementHtml(AbstractElement $element): string
|
||||
{
|
||||
$element->setDateFormat('yyyy-MM-dd');
|
||||
|
||||
return parent::_getElementHtml($element);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FreeGift\Block\Adminhtml\System\Config\Form\Field;
|
||||
|
||||
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
|
||||
use Magento\Framework\Data\Form\Element\AbstractElement;
|
||||
|
||||
class TierItems extends AbstractFieldArray
|
||||
{
|
||||
public function render(AbstractElement $element): string
|
||||
{
|
||||
$isCheckboxRequired = $this->_isInheritCheckboxRequired($element);
|
||||
if ($element->getInherit() == 1 && $isCheckboxRequired) {
|
||||
$element->setDisabled(true);
|
||||
}
|
||||
if ($element->getIsDisableInheritance()) {
|
||||
$element->setReadonly(true);
|
||||
}
|
||||
|
||||
$html = '<td class="value" colspan="2">' . $this->_getElementHtml($element);
|
||||
if ($element->getComment()) {
|
||||
$html .= '<p class="note"><span>' . $element->getComment() . '</span></p>';
|
||||
}
|
||||
$html .= '</td>';
|
||||
if ($isCheckboxRequired) {
|
||||
$html .= $this->_renderInheritCheckbox($element);
|
||||
}
|
||||
|
||||
return $this->_decorateRowHtml($element, $html);
|
||||
}
|
||||
|
||||
protected function _prepareToRender(): void
|
||||
{
|
||||
$this->addColumn('amount', [
|
||||
'label' => __('Cart Amount'),
|
||||
'class' => 'validate-number validate-zero-or-greater',
|
||||
'style' => 'width:240px',
|
||||
]);
|
||||
$this->addColumn('qty', [
|
||||
'label' => __('Gift Quantity'),
|
||||
'class' => 'validate-digits validate-greater-than-zero',
|
||||
'style' => 'width:200px',
|
||||
]);
|
||||
$this->_addAfter = false;
|
||||
$this->_addButtonLabel = __('Add Tier');
|
||||
}
|
||||
|
||||
public function getArrayRows(): array
|
||||
{
|
||||
$element = $this->getElement();
|
||||
if (!$element->getValue()) {
|
||||
$element->setValue([
|
||||
'_tier_1' => ['amount' => '199', 'qty' => '1'],
|
||||
'_tier_2' => ['amount' => '299', 'qty' => '2'],
|
||||
'_tier_3' => ['amount' => '399', 'qty' => '3'],
|
||||
]);
|
||||
}
|
||||
|
||||
return parent::getArrayRows();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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--;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FreeGift\Observer;
|
||||
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
use Magento\Quote\Model\Quote;
|
||||
|
||||
class ValidateGiftBeforeSubmit implements ObserverInterface
|
||||
{
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
$quote = $observer->getEvent()->getQuote();
|
||||
if (!$quote instanceof Quote || !(int)$quote->getStoreId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$quote->setTotalsCollectedFlag(false);
|
||||
$quote->collectTotals();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FreeGift\Plugin\CustomerData;
|
||||
|
||||
use Esun\FreeGift\Model\Config;
|
||||
use Esun\FreeGift\Model\GiftItem;
|
||||
use Magento\Checkout\CustomerData\Cart;
|
||||
use Magento\Checkout\Model\Session as CheckoutSession;
|
||||
|
||||
class CartPlugin
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CheckoutSession $checkoutSession,
|
||||
private readonly Config $config
|
||||
) {
|
||||
}
|
||||
|
||||
public function afterGetSectionData(Cart $subject, array $result): array
|
||||
{
|
||||
$giftItemIds = [];
|
||||
|
||||
$quote = $this->checkoutSession->getQuote();
|
||||
$storeId = (int)$quote->getStoreId();
|
||||
|
||||
foreach ($quote->getAllVisibleItems() as $quoteItem) {
|
||||
if ((bool)$quoteItem->getData(GiftItem::FLAG)
|
||||
|| $this->config->isGiftSku((string)$quoteItem->getSku(), $storeId)
|
||||
) {
|
||||
$giftItemIds[(int)$quoteItem->getId()] = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($result['items']) || !is_array($result['items'])) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
foreach ($result['items'] as &$item) {
|
||||
$isGift = (bool)($item['is_esun_free_gift'] ?? false)
|
||||
|| isset($giftItemIds[(int)($item['item_id'] ?? 0)])
|
||||
|| $this->config->isGiftSku((string)($item['product_sku'] ?? ''), $storeId);
|
||||
$item['is_esun_free_gift'] = $isGift;
|
||||
|
||||
if ($isGift) {
|
||||
$item['line_total'] = (string)__('Free');
|
||||
$item['original_price'] = '';
|
||||
$item['product_price'] = (string)__('Free');
|
||||
$item['product_price_value'] = 0;
|
||||
$item['product_url'] = '';
|
||||
$item['product_has_url'] = false;
|
||||
$item['configure_url'] = '';
|
||||
}
|
||||
}
|
||||
unset($item);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FreeGift\Plugin\Quote;
|
||||
|
||||
use Esun\FreeGift\Model\Config;
|
||||
use Esun\FreeGift\Model\InternalAddGuard;
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Quote\Model\Quote;
|
||||
|
||||
class AddProductPlugin
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly InternalAddGuard $internalAddGuard
|
||||
) {
|
||||
}
|
||||
|
||||
public function beforeAddProduct(
|
||||
Quote $subject,
|
||||
Product $product,
|
||||
mixed $request = null,
|
||||
string $processMode = \Magento\Catalog\Model\Product\Type\AbstractType::PROCESS_MODE_FULL
|
||||
): ?array {
|
||||
$storeId = (int)($subject->getStoreId() ?: $product->getStoreId());
|
||||
|
||||
if ($this->config->isGiftSku((string)$product->getSku(), $storeId)
|
||||
&& !$this->internalAddGuard->isAllowed()
|
||||
) {
|
||||
throw new LocalizedException(__('This promotional gift cannot be purchased separately.'));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FreeGift\Plugin\Quote;
|
||||
|
||||
use Esun\FreeGift\Model\GiftItem;
|
||||
use Esun\FreeGift\Model\GiftSynchronizer;
|
||||
use Magento\Quote\Model\Quote;
|
||||
use Magento\Quote\Model\Quote\Address\Total;
|
||||
use Magento\Quote\Model\Quote\TotalsCollector;
|
||||
|
||||
class TotalsCollectorPlugin
|
||||
{
|
||||
public function __construct(
|
||||
private readonly GiftSynchronizer $giftSynchronizer
|
||||
) {
|
||||
}
|
||||
|
||||
public function aroundCollect(
|
||||
TotalsCollector $subject,
|
||||
callable $proceed,
|
||||
Quote $quote
|
||||
): Total {
|
||||
if ((bool)$quote->getData(GiftItem::TOTALS_GUARD)) {
|
||||
return $proceed($quote);
|
||||
}
|
||||
|
||||
$quote->setData(GiftItem::TOTALS_GUARD, 1);
|
||||
|
||||
try {
|
||||
/** @var Total $total */
|
||||
$total = $proceed($quote);
|
||||
$eligibleBaseSubtotal = (float)$total->getBaseSubtotalWithDiscount();
|
||||
|
||||
if ($this->giftSynchronizer->synchronize($quote, $eligibleBaseSubtotal)) {
|
||||
/** @var Total $total */
|
||||
$total = $proceed($quote);
|
||||
}
|
||||
|
||||
return $total;
|
||||
} finally {
|
||||
$quote->unsetData(GiftItem::TOTALS_GUARD);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FreeGift\Test\Unit\Model;
|
||||
|
||||
use Esun\FreeGift\Model\Config;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class ConfigTest extends TestCase
|
||||
{
|
||||
#[DataProvider('thresholdProvider')]
|
||||
public function testTargetQuantityUsesConfiguredTiers(float $subtotal, int $expectedQuantity): void
|
||||
{
|
||||
$config = $this->createConfig(true);
|
||||
|
||||
self::assertSame($expectedQuantity, $config->getTargetQuantity($subtotal, 16));
|
||||
}
|
||||
|
||||
public static function thresholdProvider(): array
|
||||
{
|
||||
return [
|
||||
'below first tier' => [198.99, 0],
|
||||
'first tier boundary' => [199.00, 1],
|
||||
'between first and second' => [298.99, 1],
|
||||
'second tier boundary' => [299.00, 2],
|
||||
'between second and third' => [398.99, 2],
|
||||
'third tier boundary' => [399.00, 3],
|
||||
'above third tier' => [1000.00, 3],
|
||||
];
|
||||
}
|
||||
|
||||
public function testDisabledCampaignReturnsNoGift(): void
|
||||
{
|
||||
self::assertSame(0, $this->createConfig(false)->getTargetQuantity(500.00, 16));
|
||||
}
|
||||
|
||||
private function createConfig(bool $enabled): Config
|
||||
{
|
||||
$values = [
|
||||
'esun_free_gift/general/gift_sku' => 'FREE-FILAMENT',
|
||||
'esun_free_gift/general/start_date' => '2026-08-01',
|
||||
'esun_free_gift/general/end_date' => '2026-08-31',
|
||||
'esun_free_gift/tiers/items' => '[{"amount":199,"qty":1},{"amount":299,"qty":2},{"amount":399,"qty":3}]',
|
||||
'esun_free_gift/tiers/tier_1_amount' => '199',
|
||||
'esun_free_gift/tiers/tier_1_qty' => '1',
|
||||
'esun_free_gift/tiers/tier_2_amount' => '299',
|
||||
'esun_free_gift/tiers/tier_2_qty' => '2',
|
||||
'esun_free_gift/tiers/tier_3_amount' => '399',
|
||||
'esun_free_gift/tiers/tier_3_qty' => '3',
|
||||
];
|
||||
|
||||
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
|
||||
$scopeConfig->method('isSetFlag')->willReturn($enabled);
|
||||
$scopeConfig->method('getValue')->willReturnCallback(
|
||||
static fn (string $path): ?string => $values[$path] ?? null
|
||||
);
|
||||
|
||||
$timezone = $this->createMock(TimezoneInterface::class);
|
||||
$timezone->method('scopeDate')->willReturn(new \DateTime('2026-08-18'));
|
||||
|
||||
return new Config($scopeConfig, $timezone, new Json());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FreeGift\Test\Unit\Model;
|
||||
|
||||
use Esun\FreeGift\Model\Config;
|
||||
use Esun\FreeGift\Model\GiftItem;
|
||||
use Esun\FreeGift\Model\GiftSynchronizer;
|
||||
use Esun\FreeGift\Model\InternalAddGuard;
|
||||
use Magento\Catalog\Api\ProductRepositoryInterface;
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\Framework\DataObjectFactory;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Quote\Model\Quote;
|
||||
use Magento\Quote\Model\Quote\Item;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class GiftSynchronizerTest extends TestCase
|
||||
{
|
||||
public function testExistingGiftQuantityAndPriceAreNormalized(): void
|
||||
{
|
||||
$config = $this->createMock(Config::class);
|
||||
$config->method('getTargetQuantity')->with(299.00, 16)->willReturn(2);
|
||||
$config->method('isGiftSku')->willReturn(true);
|
||||
|
||||
$product = $this->getMockBuilder(Product::class)
|
||||
->disableOriginalConstructor()
|
||||
->addMethods(['setIsSuperMode'])
|
||||
->getMock();
|
||||
$product->expects(self::once())->method('setIsSuperMode')->with(true);
|
||||
|
||||
$item = $this->getMockBuilder(Item::class)
|
||||
->disableOriginalConstructor()
|
||||
->onlyMethods([
|
||||
'getData',
|
||||
'getQty',
|
||||
'getProduct',
|
||||
'setQty',
|
||||
'setCustomPrice',
|
||||
'setOriginalPrice'
|
||||
])
|
||||
->addMethods([
|
||||
'getCustomPrice',
|
||||
'setOriginalCustomPrice',
|
||||
'setBaseOriginalPrice',
|
||||
'setNoDiscount',
|
||||
'setDiscountAmount',
|
||||
'setBaseDiscountAmount',
|
||||
'setAppliedRuleIds'
|
||||
])
|
||||
->getMock();
|
||||
$item->method('getData')->willReturnCallback(
|
||||
static fn (string $key): mixed => $key === GiftItem::FLAG ? 1 : 'FREE-FILAMENT'
|
||||
);
|
||||
$item->method('getQty')->willReturn(1.0);
|
||||
$item->method('getCustomPrice')->willReturn(0.0);
|
||||
$item->method('getProduct')->willReturn($product);
|
||||
$item->expects(self::once())->method('setQty')->with(2);
|
||||
$item->expects(self::once())->method('setCustomPrice')->with(0.0);
|
||||
$item->expects(self::once())->method('setNoDiscount')->with(1);
|
||||
|
||||
$quote = $this->createMock(Quote::class);
|
||||
$quote->method('getStoreId')->willReturn(16);
|
||||
$quote->method('getAllVisibleItems')->willReturn([$item]);
|
||||
|
||||
self::assertTrue($this->createSynchronizer($config)->synchronize($quote, 299.00));
|
||||
}
|
||||
|
||||
public function testGiftIsRemovedWhenCartDropsBelowThreshold(): void
|
||||
{
|
||||
$config = $this->createMock(Config::class);
|
||||
$config->method('getTargetQuantity')->with(198.99, 16)->willReturn(0);
|
||||
|
||||
$item = $this->createMock(Item::class);
|
||||
$item->method('getData')->with(GiftItem::FLAG)->willReturn(1);
|
||||
|
||||
$quote = $this->createMock(Quote::class);
|
||||
$quote->method('getStoreId')->willReturn(16);
|
||||
$quote->method('getAllVisibleItems')->willReturn([$item]);
|
||||
$quote->expects(self::once())->method('deleteItem')->with($item);
|
||||
|
||||
self::assertTrue($this->createSynchronizer($config)->synchronize($quote, 198.99));
|
||||
}
|
||||
|
||||
private function createSynchronizer(Config $config): GiftSynchronizer
|
||||
{
|
||||
return new GiftSynchronizer(
|
||||
$config,
|
||||
$this->createMock(ProductRepositoryInterface::class),
|
||||
$this->createMock(DataObjectFactory::class),
|
||||
new Json(),
|
||||
new InternalAddGuard(),
|
||||
$this->createMock(LoggerInterface::class)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FreeGift\Test\Unit\Model;
|
||||
|
||||
use Esun\FreeGift\Model\InternalAddGuard;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class InternalAddGuardTest extends TestCase
|
||||
{
|
||||
public function testExecuteAllowsOnlyTheWrappedCallback(): void
|
||||
{
|
||||
$guard = new InternalAddGuard();
|
||||
|
||||
self::assertFalse($guard->isAllowed());
|
||||
self::assertTrue($guard->execute(static fn (): bool => $guard->isAllowed()));
|
||||
self::assertFalse($guard->isAllowed());
|
||||
}
|
||||
|
||||
public function testGuardIsResetWhenCallbackThrows(): void
|
||||
{
|
||||
$guard = new InternalAddGuard();
|
||||
|
||||
try {
|
||||
$guard->execute(static function (): void {
|
||||
throw new \RuntimeException('Expected test exception');
|
||||
});
|
||||
} catch (\RuntimeException) {
|
||||
self::assertFalse($guard->isAllowed());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\FreeGift\Test\Unit\Plugin\CustomerData;
|
||||
|
||||
use Esun\FreeGift\Model\Config;
|
||||
use Esun\FreeGift\Plugin\CustomerData\CartPlugin;
|
||||
use Magento\Checkout\CustomerData\Cart;
|
||||
use Magento\Checkout\Model\Session as CheckoutSession;
|
||||
use Magento\Quote\Model\Quote;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class CartPluginTest extends TestCase
|
||||
{
|
||||
public function testGiftSkuFallbackLocksMinicartItemAndUsesFreeLabel(): void
|
||||
{
|
||||
$quote = $this->createMock(Quote::class);
|
||||
$quote->method('getStoreId')->willReturn(16);
|
||||
$quote->method('getAllVisibleItems')->willReturn([]);
|
||||
|
||||
$checkoutSession = $this->createMock(CheckoutSession::class);
|
||||
$checkoutSession->method('getQuote')->willReturn($quote);
|
||||
|
||||
$config = $this->createMock(Config::class);
|
||||
$config->expects(self::once())
|
||||
->method('isGiftSku')
|
||||
->with('free-gift', 16)
|
||||
->willReturn(true);
|
||||
|
||||
$plugin = new CartPlugin($checkoutSession, $config);
|
||||
$result = $plugin->afterGetSectionData(
|
||||
$this->createMock(Cart::class),
|
||||
[
|
||||
'items' => [[
|
||||
'item_id' => 42,
|
||||
'product_sku' => 'free-gift',
|
||||
'product_url' => 'https://example.test/free-gift',
|
||||
'product_has_url' => true,
|
||||
'configure_url' => 'https://example.test/configure',
|
||||
'product_price' => '$0.00',
|
||||
'product_price_value' => 0.0,
|
||||
]],
|
||||
]
|
||||
);
|
||||
|
||||
$item = $result['items'][0];
|
||||
self::assertTrue($item['is_esun_free_gift']);
|
||||
self::assertSame('Free', (string)$item['line_total']);
|
||||
self::assertSame('Free', (string)$item['product_price']);
|
||||
self::assertSame('', $item['product_url']);
|
||||
self::assertFalse($item['product_has_url']);
|
||||
self::assertSame('', $item['configure_url']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
|
||||
<acl>
|
||||
<resources>
|
||||
<resource id="Magento_Backend::admin">
|
||||
<resource id="Magento_Backend::stores">
|
||||
<resource id="Magento_Backend::stores_settings">
|
||||
<resource id="Magento_Config::config">
|
||||
<resource id="Esun_FreeGift::config"
|
||||
title="eSUN Automatic Free Gift Configuration"
|
||||
sortOrder="95"/>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resources>
|
||||
</acl>
|
||||
</config>
|
||||
@@ -0,0 +1,69 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
|
||||
<system>
|
||||
<tab id="esun" translate="label" sortOrder="300">
|
||||
<label>Esun</label>
|
||||
</tab>
|
||||
<section id="esun_free_gift" translate="label" type="text" sortOrder="940"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>Automatic Free Gift</label>
|
||||
<tab>esun</tab>
|
||||
<resource>Esun_FreeGift::config</resource>
|
||||
<group id="general" translate="label" type="text" sortOrder="10"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>General</label>
|
||||
|
||||
<field id="enabled" translate="label comment" type="select" sortOrder="10"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>Enabled</label>
|
||||
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
|
||||
<config_path>esun_free_gift/general/enabled</config_path>
|
||||
</field>
|
||||
<field id="gift_sku" translate="label comment" type="text" sortOrder="20"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>Gift Product SKU</label>
|
||||
<comment>The product must be an enabled simple product assigned to this website. Set Manage Stock to No and Visibility to Not Visible Individually.</comment>
|
||||
<validate>required-entry</validate>
|
||||
<config_path>esun_free_gift/general/gift_sku</config_path>
|
||||
<depends>
|
||||
<field id="enabled">1</field>
|
||||
</depends>
|
||||
</field>
|
||||
<field id="start_date" translate="label comment" type="date" sortOrder="30"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>Start Date</label>
|
||||
<comment>Leave empty to start immediately.</comment>
|
||||
<frontend_model>Esun\FreeGift\Block\Adminhtml\System\Config\Form\Field\Date</frontend_model>
|
||||
<config_path>esun_free_gift/general/start_date</config_path>
|
||||
<depends>
|
||||
<field id="enabled">1</field>
|
||||
</depends>
|
||||
</field>
|
||||
<field id="end_date" translate="label comment" type="date" sortOrder="40"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>End Date</label>
|
||||
<comment>Leave empty for no end date.</comment>
|
||||
<frontend_model>Esun\FreeGift\Block\Adminhtml\System\Config\Form\Field\Date</frontend_model>
|
||||
<config_path>esun_free_gift/general/end_date</config_path>
|
||||
<depends>
|
||||
<field id="enabled">1</field>
|
||||
</depends>
|
||||
</field>
|
||||
|
||||
<group id="tiers" translate="label" type="text" sortOrder="50"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>Gift Tiers</label>
|
||||
<field id="items" translate="label comment" sortOrder="10"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>Tier Items</label>
|
||||
<frontend_model>Esun\FreeGift\Block\Adminhtml\System\Config\Form\Field\TierItems</frontend_model>
|
||||
<backend_model>Esun\FreeGift\Model\Config\Backend\TierItems</backend_model>
|
||||
<comment>Compared with the base subtotal after discounts, excluding tax, shipping and gift items. Tiers are evaluated from the highest amount down.</comment>
|
||||
<config_path>esun_free_gift/tiers/items</config_path>
|
||||
</field>
|
||||
</group>
|
||||
</group>
|
||||
</section>
|
||||
</system>
|
||||
</config>
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
|
||||
<default>
|
||||
<esun_free_gift>
|
||||
<general>
|
||||
<enabled>0</enabled>
|
||||
<gift_sku></gift_sku>
|
||||
<start_date></start_date>
|
||||
<end_date></end_date>
|
||||
</general>
|
||||
<tiers>
|
||||
<tier_1_amount>199</tier_1_amount>
|
||||
<tier_1_qty>1</tier_1_qty>
|
||||
<tier_2_amount>299</tier_2_amount>
|
||||
<tier_2_qty>2</tier_2_qty>
|
||||
<tier_3_amount>399</tier_3_amount>
|
||||
<tier_3_qty>3</tier_3_qty>
|
||||
</tiers>
|
||||
</esun_free_gift>
|
||||
</default>
|
||||
</config>
|
||||
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0"?>
|
||||
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
|
||||
<table name="quote_item" resource="checkout" engine="innodb" comment="Sales Flat Quote Item">
|
||||
<column xsi:type="smallint"
|
||||
name="is_esun_free_gift"
|
||||
unsigned="true"
|
||||
nullable="false"
|
||||
default="0"
|
||||
comment="Is eSUN Automatic Free Gift"/>
|
||||
</table>
|
||||
<table name="sales_order_item" resource="sales" engine="innodb" comment="Sales Flat Order Item">
|
||||
<column xsi:type="smallint"
|
||||
name="is_esun_free_gift"
|
||||
unsigned="true"
|
||||
nullable="false"
|
||||
default="0"
|
||||
comment="Is eSUN Automatic Free Gift"/>
|
||||
</table>
|
||||
</schema>
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"quote_item": {
|
||||
"column": {
|
||||
"is_esun_free_gift": true
|
||||
}
|
||||
},
|
||||
"sales_order_item": {
|
||||
"column": {
|
||||
"is_esun_free_gift": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
|
||||
<type name="Magento\Quote\Model\Quote">
|
||||
<plugin name="esun_free_gift_block_external_add"
|
||||
type="Esun\FreeGift\Plugin\Quote\AddProductPlugin"
|
||||
sortOrder="10"/>
|
||||
</type>
|
||||
<type name="Magento\Quote\Model\Quote\TotalsCollector">
|
||||
<plugin name="esun_free_gift_sync_during_totals"
|
||||
type="Esun\FreeGift\Plugin\Quote\TotalsCollectorPlugin"
|
||||
sortOrder="100"/>
|
||||
</type>
|
||||
</config>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
|
||||
<event name="sales_model_service_quote_submit_before">
|
||||
<observer name="esun_free_gift_validate_before_submit"
|
||||
instance="Esun\FreeGift\Observer\ValidateGiftBeforeSubmit"/>
|
||||
</event>
|
||||
</config>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Object/etc/fieldset.xsd">
|
||||
<scope id="global">
|
||||
<fieldset id="sales_convert_quote_item">
|
||||
<field name="is_esun_free_gift">
|
||||
<aspect name="to_order_item"/>
|
||||
</field>
|
||||
</fieldset>
|
||||
</scope>
|
||||
</config>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
|
||||
<type name="Magento\Checkout\CustomerData\Cart">
|
||||
<plugin name="esun_free_gift_customer_data"
|
||||
type="Esun\FreeGift\Plugin\CustomerData\CartPlugin"
|
||||
sortOrder="10000"/>
|
||||
</type>
|
||||
</config>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
|
||||
<module name="Esun_FreeGift">
|
||||
<sequence>
|
||||
<module name="Magento_Catalog"/>
|
||||
<module name="Magento_Checkout"/>
|
||||
<module name="Magento_Quote"/>
|
||||
<module name="Magento_Sales"/>
|
||||
<module name="Esun_Cart"/>
|
||||
</sequence>
|
||||
</module>
|
||||
</config>
|
||||
@@ -0,0 +1,4 @@
|
||||
"Promotion","Promotion"
|
||||
"Free Gift","Free Gift"
|
||||
"This promotional gift cannot be purchased separately.","This promotional gift cannot be purchased separately."
|
||||
"The configured free gift must be a simple product.","The configured free gift must be a simple product."
|
||||
|
@@ -0,0 +1,4 @@
|
||||
"Promotion","促销活动"
|
||||
"Free Gift","活动赠品"
|
||||
"This promotional gift cannot be purchased separately.","该活动赠品不能单独购买。"
|
||||
"The configured free gift must be a simple product.","配置的赠品必须是简单商品。"
|
||||
|
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Magento\Framework\Component\ComponentRegistrar;
|
||||
|
||||
ComponentRegistrar::register(
|
||||
ComponentRegistrar::MODULE,
|
||||
'Esun_FreeGift',
|
||||
__DIR__
|
||||
);
|
||||
Reference in New Issue
Block a user