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