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,14 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model;
use Magento\Framework\Model\AbstractModel;
class Assignment extends AbstractModel
{
protected function _construct(): void
{
$this->_init(\Esun\CustomerCoupon\Model\ResourceModel\Assignment::class);
}
}
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model;
use Esun\CustomerCoupon\Api\CouponNotifierInterface;
use Esun\CustomerCoupon\Model\ResourceModel\Assignment as AssignmentResource;
use Magento\Framework\Exception\LocalizedException;
use Magento\SalesRule\Model\CouponFactory;
class AssignmentService
{
public function __construct(
private readonly AssignmentFactory $assignmentFactory,
private readonly AssignmentResource $assignmentResource,
private readonly CouponFactory $couponFactory,
private readonly CouponNotifierInterface $couponNotifier
) {
}
/**
* Assign generated coupon codes to customers.
*
* @param string[] $codes
* @param int[] $customerIds
* @param int $ruleId
* @param string|null $source Stable source key used to make automatic grants idempotent
*/
public function assignCodes(array $codes, array $customerIds, int $ruleId, ?string $source = null): void
{
if (count($codes) !== count($customerIds)) {
throw new LocalizedException(__('The generated coupon count does not match the selected customer count.'));
}
$connection = $this->assignmentResource->getConnection();
$assignmentIds = [];
$connection->beginTransaction();
try {
foreach (array_values($codes) as $index => $code) {
$coupon = $this->couponFactory->create()->load($code, 'code');
if (!$coupon->getId()) {
throw new LocalizedException(__('The generated coupon "%1" could not be loaded.', $code));
}
$assignment = $this->assignmentFactory->create();
$assignment->setData([
'coupon_id' => (int)$coupon->getId(),
'rule_id' => $ruleId,
'customer_id' => (int)$customerIds[$index],
'source' => $source,
]);
$this->assignmentResource->save($assignment);
$assignmentIds[] = (int)$assignment->getId();
}
$connection->commit();
} catch (\Throwable $exception) {
$connection->rollBack();
throw $exception;
}
foreach ($assignmentIds as $assignmentId) {
try {
$this->couponNotifier->notify($assignmentId);
} catch (\Throwable) {
// Notification delivery is best-effort and must not invalidate an assigned coupon.
}
}
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class Config
{
private const XML_PATH_REGISTRATION_SUBSCRIPTION_RULE =
'esun_customer_coupon/registration_subscription/rule_id';
public function __construct(private readonly ScopeConfigInterface $scopeConfig)
{
}
public function getRegistrationSubscriptionRuleId(?int $storeId = null): int
{
return (int)$this->scopeConfig->getValue(
self::XML_PATH_REGISTRATION_SUBSCRIPTION_RULE,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory;
use Magento\SalesRule\Model\Rule;
class AutoGeneratedCartRule implements OptionSourceInterface
{
public function __construct(private readonly CollectionFactory $collectionFactory)
{
}
/**
* Return active cart rules that support generated coupon codes.
*
* @return array<int, array{value: int|string, label: \Stringable|string}>
*/
public function toOptionArray(): array
{
$collection = $this->collectionFactory->create();
$collection->addFieldToSelect(['rule_id', 'name', 'coupon_type', 'use_auto_generation']);
$collection->addFieldToFilter('is_active', 1);
$collection->addFieldToFilter(
['coupon_type', 'use_auto_generation'],
[['eq' => Rule::COUPON_TYPE_AUTO], ['eq' => 1]]
);
$collection->setOrder('name', 'ASC');
$options = [['value' => '', 'label' => __('-- Disabled --')]];
foreach ($collection as $rule) {
$options[] = [
'value' => (int)$rule->getId(),
'label' => sprintf('%s (ID: %d)', (string)$rule->getName(), (int)$rule->getId()),
];
}
return $options;
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model\Coupon;
use Magento\SalesRule\Model\Rule;
class ConditionFormatter
{
/** @return string[] */
public function format(Rule $rule): array
{
$description = trim(strip_tags((string)$rule->getDescription()));
return $description === '' ? [] : [$description];
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model\Coupon;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\SalesRule\Model\Rule;
class DiscountFormatter
{
public function __construct(private readonly PriceCurrencyInterface $priceCurrency)
{
}
public function format(Rule $rule): string
{
$amount = (float)$rule->getDiscountAmount();
return match ((string)$rule->getSimpleAction()) {
Rule::BY_PERCENT_ACTION => (string)__('%1% OFF', $this->formatNumber($amount)),
Rule::TO_PERCENT_ACTION => (string)__('Pay %1% of the item price', $this->formatNumber($amount)),
Rule::BY_FIXED_ACTION => (string)__(
'%1 OFF eligible items',
$this->priceCurrency->convertAndFormat($amount, false)
),
Rule::TO_FIXED_ACTION => (string)__(
'Eligible items for %1',
$this->priceCurrency->convertAndFormat($amount, false)
),
Rule::CART_FIXED_ACTION => (string)__(
'%1 OFF',
$this->priceCurrency->convertAndFormat($amount, false)
),
Rule::BUY_X_GET_Y_ACTION => (string)__(
'Buy %1, get %2 free',
max(1, (int)$rule->getDiscountStep()),
max(1, (int)$amount)
),
default => (string)__('Special offer'),
};
}
private function formatNumber(float $number): string
{
return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model\Coupon;
use Magento\Quote\Model\Quote;
use Magento\SalesRule\Model\Rule;
class EligibilityService
{
public function isApplicableToQuote(Rule $rule, Quote $quote): bool
{
if (!$quote->getItemsCount()) {
return false;
}
$address = $quote->getIsVirtual() ? $quote->getBillingAddress() : $quote->getShippingAddress();
if (!$rule->getConditions()->validate($address)) {
return false;
}
if (!$rule->getActions()->getConditions()) {
return true;
}
foreach ($quote->getAllVisibleItems() as $item) {
if ($rule->getActions()->validate($item)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model\Coupon;
use Esun\CustomerCoupon\Model\ResourceModel\Assignment\CollectionFactory;
use Magento\Quote\Model\Quote;
use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory as RuleCollectionFactory;
use Magento\SalesRule\Model\Rule;
class ListProvider
{
public function __construct(
private readonly CollectionFactory $assignmentCollectionFactory,
private readonly RuleCollectionFactory $ruleCollectionFactory,
private readonly StatusResolver $statusResolver,
private readonly DiscountFormatter $discountFormatter,
private readonly ConditionFormatter $conditionFormatter,
private readonly EligibilityService $eligibilityService
) {
}
/** @return array<int,array<string,mixed>> */
public function getForCustomer(
int $customerId,
int $websiteId,
int $customerGroupId,
?Quote $quote = null
): array {
$collection = $this->assignmentCollectionFactory->create();
$collection->addFieldToFilter('main_table.customer_id', $customerId);
$collection->getSelect()
->joinInner(
['coupon' => $collection->getTable('salesrule_coupon')],
'main_table.coupon_id = coupon.coupon_id',
[
'code', 'usage_limit', 'usage_per_customer', 'times_used', 'expiration_date',
]
)
->joinLeft(
['coupon_usage' => $collection->getTable('salesrule_coupon_usage')],
'coupon_usage.coupon_id = main_table.coupon_id'
. ' AND coupon_usage.customer_id = main_table.customer_id',
['customer_times_used' => 'times_used']
)
->order('main_table.assigned_at DESC');
$ruleIds = array_values(array_unique(array_map(
'intval',
$collection->getColumnValues('rule_id')
)));
if (!$ruleIds) {
return [];
}
$rules = [];
$ruleCollection = $this->ruleCollectionFactory->create()->addFieldToFilter('rule_id', ['in' => $ruleIds]);
foreach ($ruleCollection as $rule) {
$rules[(int)$rule->getId()] = $rule;
}
$result = [];
foreach ($collection as $assignment) {
/** @var Rule|null $rule */
$rule = $rules[(int)$assignment->getData('rule_id')] ?? null;
if (!$rule) {
continue;
}
$data = $assignment->getData();
$data['customer_times_used'] = (int)($data['customer_times_used'] ?? 0);
$status = $this->statusResolver->resolve($data, $rule, $websiteId, $customerGroupId);
$cartApplicable = $status['status'] === 'available'
&& ($quote === null || $this->eligibilityService->isApplicableToQuote($rule, $quote));
$storeLabel = trim((string)$rule->getStoreLabel());
$result[] = [
'assignment_id' => (int)$assignment->getId(),
'code' => (string)$assignment->getData('code'),
'rule_name' => $storeLabel,
'discount_label' => $this->discountFormatter->format($rule),
'conditions' => $this->conditionFormatter->format($rule),
'expires_at' => $status['expires_at'],
'status' => $status['status'],
'status_reason' => $status['reason'],
'cart_applicable' => $cartApplicable,
];
}
return $result;
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model\Coupon;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\SalesRule\Model\Rule;
class StatusResolver
{
public function __construct(private readonly TimezoneInterface $timezone)
{
}
/** @return array{status:string,reason:?string,expires_at:?string} */
public function resolve(array $couponData, Rule $rule, int $websiteId, int $customerGroupId): array
{
$today = $this->timezone->date()->format('Y-m-d');
$expiresAt = $this->getEffectiveExpiration($couponData, $rule);
$reason = null;
if (!(bool)$rule->getIsActive()) {
$reason = (string)__('Promotion is inactive');
} elseif ($rule->getFromDate() && (string)$rule->getFromDate() > $today) {
$reason = (string)__('Promotion has not started');
} elseif ($expiresAt && $expiresAt < $today) {
$reason = (string)__('Expired');
} elseif (!in_array($websiteId, array_map('intval', $rule->getWebsiteIds()), true)) {
$reason = (string)__('Not available on this website');
} elseif (!in_array($customerGroupId, array_map('intval', $rule->getCustomerGroupIds()), true)) {
$reason = (string)__('Not available for your customer group');
} elseif ((int)$couponData['usage_limit'] > 0
&& (int)$couponData['times_used'] >= (int)$couponData['usage_limit']) {
$reason = (string)__('Usage limit reached');
} elseif ((int)$couponData['usage_per_customer'] > 0
&& (int)$couponData['customer_times_used'] >= (int)$couponData['usage_per_customer']) {
$reason = (string)__('Used');
}
return [
'status' => $reason === null ? 'available' : 'unavailable',
'reason' => $reason,
'expires_at' => $expiresAt,
];
}
private function getEffectiveExpiration(array $couponData, Rule $rule): ?string
{
$dates = [];
if ($rule->getToDate()) {
$dates[] = substr((string)$rule->getToDate(), 0, 10);
}
if (!empty($couponData['expiration_date'])) {
$dates[] = substr((string)$couponData['expiration_date'], 0, 10);
}
return $dates ? min($dates) : null;
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model\Notification;
use Esun\CustomerCoupon\Api\CouponNotifierInterface;
class NullCouponNotifier implements CouponNotifierInterface
{
public function notify(int $assignmentId): void
{
// Intentionally empty. A mail or webhook adapter can replace this implementation later.
}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model;
use Magento\Customer\Model\Session;
class RegistrationCouponGrantContext
{
private const SESSION_KEY = 'esun_registration_coupon_granted_customer_id';
public function __construct(private readonly Session $customerSession)
{
}
public function markGranted(int $customerId): void
{
if ($customerId > 0) {
$this->customerSession->setData(self::SESSION_KEY, $customerId);
}
}
public function consumeGrantedCustomerId(): int
{
$customerId = (int)$this->customerSession->getData(self::SESSION_KEY);
$this->customerSession->unsetData(self::SESSION_KEY);
return $customerId;
}
}
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model;
use Esun\CustomerCoupon\Model\ResourceModel\Assignment as AssignmentResource;
use Esun\PromotionPopup\Model\Config as PromotionConfig;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\SalesRule\Api\CouponManagementInterface;
use Magento\SalesRule\Api\Data\CouponGenerationSpecInterface;
use Magento\SalesRule\Api\Data\CouponGenerationSpecInterfaceFactory;
use Magento\SalesRule\Model\Rule;
use Magento\SalesRule\Model\RuleFactory;
use Magento\Store\Model\StoreManagerInterface;
class RegistrationSubscriptionCouponService
{
public const ASSIGNMENT_SOURCE = 'registration_newsletter';
public function __construct(
private readonly Config $config,
private readonly RuleFactory $ruleFactory,
private readonly CouponGenerationSpecInterfaceFactory $generationSpecFactory,
private readonly CouponManagementInterface $couponManagement,
private readonly AssignmentService $assignmentService,
private readonly AssignmentResource $assignmentResource,
private readonly TimezoneInterface $timezone,
private readonly StoreManagerInterface $storeManager,
private readonly PromotionConfig $promotionConfig
) {
}
/**
* Generate and assign the one-time registration subscription coupon.
*
* @throws LocalizedException
*/
public function grant(int $customerId, int $websiteId, int $customerGroupId, int $storeId): bool
{
if ($customerId <= 0
|| !$this->promotionConfig->isCampaignActive()
|| !$this->promotionConfig->isRegistrationNewsletterCouponPromotion()
|| $this->hasAlreadyBeenGranted($customerId)
) {
return false;
}
$ruleId = $this->config->getRegistrationSubscriptionRuleId($storeId ?: null);
if ($ruleId <= 0) {
return false;
}
/** @var Rule $rule */
$rule = $this->ruleFactory->create()->load($ruleId);
$scope = $storeId > 0 ? $this->storeManager->getStore($storeId) : $this->storeManager->getStore();
if (!$rule->getId()
|| !$rule->getIsActive()
|| ((int)$rule->getCouponType() !== Rule::COUPON_TYPE_AUTO && !$rule->getUseAutoGeneration())
|| !in_array($websiteId, array_map('intval', $rule->getWebsiteIds()), true)
|| !in_array($customerGroupId, array_map('intval', $rule->getCustomerGroupIds()), true)
|| !$this->timezone->isScopeDateInInterval($scope, $rule->getFromDate(), $rule->getToDate())
) {
throw new LocalizedException(
__('The configured registration subscription coupon rule is not eligible for this customer.')
);
}
/** @var CouponGenerationSpecInterface $specification */
$specification = $this->generationSpecFactory->create();
$specification->setRuleId($ruleId)
->setQuantity(1)
->setLength(12)
->setFormat(CouponGenerationSpecInterface::COUPON_FORMAT_ALPHANUMERIC)
->setPrefix('WELCOME-')
->setDelimiterAtEvery(0);
$codes = $this->couponManagement->generate($specification);
if (count($codes) !== 1) {
if ($codes) {
$this->couponManagement->deleteByCodes($codes);
}
throw new LocalizedException(__('The registration subscription coupon could not be generated.'));
}
try {
$this->assignmentService->assignCodes(
$codes,
[$customerId],
$ruleId,
self::ASSIGNMENT_SOURCE
);
} catch (\Throwable $exception) {
$this->couponManagement->deleteByCodes($codes);
if ($this->hasAlreadyBeenGranted($customerId)) {
return true;
}
throw $exception;
}
return true;
}
private function hasAlreadyBeenGranted(int $customerId): bool
{
$connection = $this->assignmentResource->getConnection();
$select = $connection->select()
->from($this->assignmentResource->getMainTable(), ['entity_id'])
->where('customer_id = ?', $customerId)
->where('source = ?', self::ASSIGNMENT_SOURCE)
->limit(1);
return (bool)$connection->fetchOne($select);
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Assignment extends AbstractDb
{
protected function _construct(): void
{
$this->_init('esun_customer_coupon', 'entity_id');
}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model\ResourceModel\Assignment;
use Esun\CustomerCoupon\Model\Assignment as AssignmentModel;
use Esun\CustomerCoupon\Model\ResourceModel\Assignment as AssignmentResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct(): void
{
$this->_init(AssignmentModel::class, AssignmentResource::class);
}
}