This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Esun\Cart\Model\Checkout;
use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Cms\Block\Block as CmsBlock;
use Magento\Framework\View\LayoutInterface;
class ServicesConfigProvider implements ConfigProviderInterface
{
private const PAYMENT_BLOCK = 'esun_product_payment_security';
private const DELIVERY_BLOCK = 'esun_product_delivery_shipping';
public function __construct(private readonly LayoutInterface $layout)
{
}
public function getConfig(): array
{
return [
'esunCartServices' => [
'paymentSecurity' => $this->renderCmsBlock(self::PAYMENT_BLOCK),
'deliveryShipping' => $this->renderCmsBlock(self::DELIVERY_BLOCK)
]
];
}
private function renderCmsBlock(string $identifier): string
{
return $this->layout->createBlock(CmsBlock::class)
->setBlockId($identifier)
->toHtml();
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Esun\Cart\Model\Config\Backend;
use Magento\Framework\App\Config\Value;
/**
* Normalizes the admin SKU list while preserving its display order.
*/
class RecommendedProductSkus extends Value
{
/**
* Normalize commas and line breaks to one unique SKU per line.
*
* @return $this
*/
public function beforeSave()
{
$skus = preg_split('/[\r\n,]+/', (string)$this->getValue()) ?: [];
$skus = array_values(array_unique(array_filter(
array_map('trim', $skus),
static fn(string $sku): bool => $sku !== ''
)));
$this->setValue(implode("\n", $skus));
return parent::beforeSave();
}
}
@@ -0,0 +1,259 @@
<?php
declare(strict_types=1);
namespace Esun\Cart\Model;
use Esun\Catalog\Model\MixStepPriceProvider;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\DataObject;
use Magento\Quote\Model\Quote;
use Magento\SalesRule\Api\Data\RuleInterface;
use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory;
use Magento\Framework\Pricing\PriceCurrencyInterface;
class MilestoneProvider
{
public function __construct(
private readonly CollectionFactory $ruleCollectionFactory,
private readonly CheckoutSession $checkoutSession,
private readonly ProductRepositoryInterface $productRepository,
private readonly MixStepPriceProvider $mixStepPriceProvider,
private readonly PriceCurrencyInterface $priceCurrency
) {
}
public function getData(?Quote $quote = null): array
{
$quote ??= $this->checkoutSession->getQuote();
$mixGroups = $this->getMixGroups($quote);
if ($mixGroups) {
return array_merge($mixGroups[0], ['groups' => $mixGroups]);
}
$quantity = (int)ceil((float)$quote->getItemsQty());
$milestones = $this->getMilestones($quote);
$maximum = $milestones ? max(array_column($milestones, 'qty')) : 0;
$active = null;
$next = null;
foreach ($milestones as &$milestone) {
$milestone['active'] = $quantity >= $milestone['qty'];
$milestone['position'] = $maximum > 0
? round(min(100, ($milestone['qty'] / $maximum) * 100), 2)
: 0;
if ($milestone['active']) {
$active = $milestone;
} elseif ($next === null) {
$next = $milestone;
}
}
unset($milestone);
return [
'quantity' => $quantity,
'progress_percent' => $maximum > 0 ? round(min(100, ($quantity / $maximum) * 100), 2) : 0,
'milestones' => $milestones,
'message' => $this->getMessage($quantity, $active, $next),
'groups' => [],
];
}
private function getMixGroups(Quote $quote): array
{
$groupedItems = [];
foreach ($quote->getAllVisibleItems() as $item) {
if ($item->getProductType() === Configurable::TYPE_CODE) {
$groupedItems[(int)$item->getProductId()][] = $item;
}
}
$groups = [];
foreach ($groupedItems as $parentProductId => $items) {
try {
$parentProduct = $this->productRepository->getById(
$parentProductId,
false,
(int)$quote->getStoreId()
);
} catch (\Magento\Framework\Exception\NoSuchEntityException) {
continue;
}
$rules = $this->mixStepPriceProvider->getRules(
$parentProduct,
(int)$quote->getCustomerGroupId()
);
if (!$rules) {
continue;
}
$quantity = (int)array_sum(array_map(
static fn ($item): float => (float)$item->getQty(),
$items
));
$milestones = [];
foreach ($rules as $rule) {
$isFixed = ($rule['price_type'] ?? '') === 'fixed';
$value = $isFixed
? $this->priceCurrency->convertAndFormat(
(float)$rule['value'],
false,
2,
$quote->getStore()
)
: $this->formatPercent((float)$rule['value']) . '% Off';
$milestones[] = [
'qty' => (int)$rule['qty'],
'type' => 'discount',
'value' => $value,
'label' => (string)__('%1 pcs', (int)$rule['qty']),
];
}
usort($milestones, static fn (array $left, array $right): int => $left['qty'] <=> $right['qty']);
$maximum = $milestones ? max(array_column($milestones, 'qty')) : 0;
$active = null;
$next = null;
foreach ($milestones as &$milestone) {
$milestone['active'] = $quantity >= $milestone['qty'];
$milestone['position'] = $maximum > 0
? round(min(100, ($milestone['qty'] / $maximum) * 100), 2)
: 0;
if ($milestone['active']) {
$active = $milestone;
} elseif ($next === null) {
$next = $milestone;
}
}
unset($milestone);
$groups[] = [
'product_id' => $parentProductId,
'name' => (string)$parentProduct->getName(),
'quantity' => $quantity,
'progress_percent' => $maximum > 0
? round(min(100, ($quantity / $maximum) * 100), 2)
: 0,
'milestones' => $milestones,
'message' => $this->getMessage($quantity, $active, $next),
];
}
return $groups;
}
private function getMilestones(Quote $quote): array
{
if (!$quote->getStoreId()) {
return [];
}
$collection = $this->ruleCollectionFactory->create();
$collection->setValidationFilter(
(int)$quote->getStore()->getWebsiteId(),
(int)$quote->getCustomerGroupId(),
(string)$quote->getCouponCode(),
null,
$quote->getShippingAddress()
);
$items = [];
foreach ($collection as $rule) {
$quantity = $this->findQuantityThreshold($rule->getConditions());
if ($quantity === null || $quantity < 1) {
continue;
}
$discountAmount = (float)$rule->getDiscountAmount();
if ($rule->getSimpleAction() === RuleInterface::DISCOUNT_ACTION_BY_PERCENT && $discountAmount > 0) {
$key = $quantity . ':discount';
$items[$key] = [
'qty' => $quantity,
'type' => 'discount',
'value' => $this->formatPercent($discountAmount) . '% Off',
'label' => (string)__('%1 pcs %2% off', $quantity, $this->formatPercent($discountAmount)),
'discount' => $discountAmount,
];
}
if ((int)$rule->getSimpleFreeShipping() > 0) {
$items[$quantity . ':free_shipping'] = [
'qty' => $quantity,
'type' => 'free_shipping',
'value' => (string)__('Free Shipping'),
'label' => (string)__('%1 pcs', $quantity),
];
}
}
$milestones = array_values($items);
usort($milestones, static function (array $left, array $right): int {
$quantityComparison = $left['qty'] <=> $right['qty'];
if ($quantityComparison !== 0) {
return $quantityComparison;
}
return $left['type'] === 'discount' ? -1 : 1;
});
return $milestones;
}
private function findQuantityThreshold(DataObject $condition): ?int
{
$thresholds = [];
$this->collectQuantityThresholds($condition, $thresholds);
return $thresholds ? max($thresholds) : null;
}
private function collectQuantityThresholds(DataObject $condition, array &$thresholds): void
{
if ((string)$condition->getData('attribute') === 'total_qty') {
$value = (float)$condition->getData('value');
$operator = (string)$condition->getData('operator');
if ($operator === '>=') {
$thresholds[] = (int)ceil($value);
} elseif ($operator === '>') {
$thresholds[] = (int)floor($value) + 1;
} elseif ($operator === '==') {
$thresholds[] = (int)round($value);
}
}
$children = method_exists($condition, 'getConditions')
? (array)$condition->getConditions()
: (array)$condition->getData('conditions');
foreach ($children as $child) {
if ($child instanceof DataObject) {
$this->collectQuantityThresholds($child, $thresholds);
}
}
}
private function getMessage(int $quantity, ?array $active, ?array $next): string
{
if ($next) {
$remaining = max(0, (int)$next['qty'] - $quantity);
$prefix = $active ? $active['value'] . ' | ' : '';
return $prefix . (string)__('Add %1 More For %2', $remaining, $next['value']);
}
if ($active) {
return (string)__('Unlocked: %1', $active['value']);
}
return '';
}
private function formatPercent(float $value): string
{
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.');
}
}
@@ -0,0 +1,146 @@
<?php
declare(strict_types=1);
namespace Esun\Cart\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\Quote\Item\AbstractItem;
use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory as RuleCollectionFactory;
use Magento\Store\Model\ScopeInterface;
class ShippingEstimate
{
private const XML_PATH_FLATRATE_ACTIVE = 'carriers/flatrate/active';
private const XML_PATH_FLATRATE_PRICE = 'carriers/flatrate/price';
private const XML_PATH_FLATRATE_TITLE = 'carriers/flatrate/title';
private const XML_PATH_FLATRATE_NAME = 'carriers/flatrate/name';
public function __construct(
private readonly ScopeConfigInterface $scopeConfig,
private readonly PriceCurrencyInterface $priceCurrency,
private readonly RuleCollectionFactory $ruleCollectionFactory
) {
}
public function getData(Quote $quote): array
{
$storeId = (int)$quote->getStoreId();
$available = $this->hasPhysicalItems($quote)
&& $this->scopeConfig->isSetFlag(
self::XML_PATH_FLATRATE_ACTIVE,
ScopeInterface::SCOPE_STORE,
$storeId
);
$freeShipping = $available && $this->isFreeShipping($quote);
$baseAmount = $available && !$freeShipping
? (float)$this->scopeConfig->getValue(
self::XML_PATH_FLATRATE_PRICE,
ScopeInterface::SCOPE_STORE,
$storeId
)
: 0.0;
$amount = $available
? (float)$this->priceCurrency->convertAndRound($baseAmount, $quote->getStore())
: 0.0;
return [
'available' => $available,
'free_shipping' => $freeShipping,
'quantity' => $this->getPhysicalQuantity($quote),
'base_amount' => $baseAmount,
'amount' => $amount,
'description' => $available ? $this->getDescription($storeId, $freeShipping) : '',
];
}
public function isFreeShipping(Quote $quote): bool
{
if (!$this->hasPhysicalItems($quote) || !$quote->getStoreId()) {
return false;
}
$address = clone $quote->getShippingAddress();
$address->setTotalQty($this->getPhysicalQuantity($quote))
->setSubtotal((float)$quote->getSubtotal())
->setBaseSubtotal((float)$quote->getBaseSubtotal());
$collection = $this->ruleCollectionFactory->create();
$collection->setValidationFilter(
(int)$quote->getStore()->getWebsiteId(),
(int)$quote->getCustomerGroupId(),
(string)$quote->getCouponCode(),
null,
$address
);
foreach ($collection as $rule) {
if ((int)$rule->getSimpleFreeShipping() > 0
&& $rule->getConditions()->validate($address)
) {
return true;
}
}
return false;
}
/**
* @param AbstractItem[] $items
*/
public function isFreeShippingForItems(array $items): bool
{
foreach ($items as $item) {
$quote = $item->getQuote();
if ($quote instanceof Quote) {
return $this->isFreeShipping($quote);
}
$addressQuote = $item->getAddress()?->getQuote();
if ($addressQuote instanceof Quote) {
return $this->isFreeShipping($addressQuote);
}
}
return false;
}
private function hasPhysicalItems(Quote $quote): bool
{
return $this->getPhysicalQuantity($quote) > 0;
}
private function getPhysicalQuantity(Quote $quote): float
{
$quantity = 0.0;
foreach ($quote->getAllVisibleItems() as $item) {
if ($item->getProduct()->isVirtual()) {
continue;
}
$quantity += (float)$item->getQty();
}
return $quantity;
}
private function getDescription(int $storeId, bool $freeShipping): string
{
if ($freeShipping) {
return (string)__('Free Shipping');
}
$title = (string)$this->scopeConfig->getValue(
self::XML_PATH_FLATRATE_TITLE,
ScopeInterface::SCOPE_STORE,
$storeId
);
$name = (string)$this->scopeConfig->getValue(
self::XML_PATH_FLATRATE_NAME,
ScopeInterface::SCOPE_STORE,
$storeId
);
return trim($title . ($title !== '' && $name !== '' ? ' - ' : '') . $name);
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Esun\Cart\Model;
use Magento\Customer\Model\Context as CustomerContext;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Store\Model\ScopeInterface;
class TestModeConfig
{
private const XML_PATH_ENABLED = 'esun_cart/test_mode/enabled';
private const XML_PATH_ALLOWED_CUSTOMER_GROUPS = 'esun_cart/test_mode/allowed_customer_groups';
private const XML_PATH_POPUP_TITLE = 'esun_cart/test_mode/popup_title';
private const XML_PATH_POPUP_MESSAGE = 'esun_cart/test_mode/popup_message';
private const DEFAULT_POPUP_TITLE = 'Test Mode';
private const DEFAULT_POPUP_MESSAGE =
'Our website is currently in beta testing. Purchases are not available at this time.';
public function __construct(
private readonly ScopeConfigInterface $scopeConfig,
private readonly HttpContext $httpContext
) {
}
public function isEnabled(): bool
{
return $this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED, ScopeInterface::SCOPE_STORE);
}
/** @return int[] */
public function getAllowedCustomerGroupIds(): array
{
$value = (string)$this->scopeConfig->getValue(
self::XML_PATH_ALLOWED_CUSTOMER_GROUPS,
ScopeInterface::SCOPE_STORE
);
if ($value === '') {
return [];
}
return array_values(array_unique(array_map('intval', array_filter(explode(',', $value), 'strlen'))));
}
public function isCurrentCustomerAllowed(): bool
{
$customerGroupId = (int)$this->httpContext->getValue(CustomerContext::CONTEXT_GROUP);
return in_array($customerGroupId, $this->getAllowedCustomerGroupIds(), true);
}
public function isRestricted(): bool
{
return $this->isEnabled() && !$this->isCurrentCustomerAllowed();
}
public function getPopupTitle(): string
{
return $this->getTextValue(self::XML_PATH_POPUP_TITLE, self::DEFAULT_POPUP_TITLE);
}
public function getPopupMessage(): string
{
return $this->getTextValue(self::XML_PATH_POPUP_MESSAGE, self::DEFAULT_POPUP_MESSAGE);
}
private function getTextValue(string $path, string $default): string
{
$value = trim((string)$this->scopeConfig->getValue($path, ScopeInterface::SCOPE_STORE));
return $value !== '' ? $value : $default;
}
}