Files
2026-09-15 10:35:56 +08:00

92 lines
3.5 KiB
PHP

<?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;
}
}