60 lines
2.3 KiB
PHP
60 lines
2.3 KiB
PHP
<?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;
|
|
}
|
|
}
|