Files
esun3d/app/code/Esun/Reward/Plugin/CustomerData/CartPlugin.php
T
2026-09-15 10:35:56 +08:00

36 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\Reward\Plugin\CustomerData;
use Esun\Reward\Model\BalanceManager;
use Esun\Reward\Model\Config;
use Magento\Checkout\CustomerData\Cart;
use Magento\Checkout\Helper\Data as CheckoutHelper;
use Magento\Checkout\Model\Cart as CheckoutCart;
use Magento\Customer\Helper\Session\CurrentCustomer;
class CartPlugin
{
public function __construct(
private readonly CheckoutCart $checkoutCart,
private readonly CurrentCustomer $currentCustomer,
private readonly BalanceManager $balances,
private readonly Config $config,
private readonly CheckoutHelper $checkoutHelper
) {}
public function afterGetSectionData(Cart $subject, array $result): array
{
// Use the same cart model and current-customer helper as Magento's cart
// and customer sections. Injecting fresh session models here can create
// a second, empty quote/session during customer/section/load.
$quote = $this->checkoutCart->getQuote();
$customerId = (int)$this->currentCustomer->getCustomerId()
?: (int)$quote->getCustomerId();
$balance = $customerId > 0 ? (int)$this->balances->getAccount($customerId, (int)$quote->getStore()->getWebsiteId())['balance'] : 0;
$result['reward'] = ['logged_in' => $customerId > 0, 'balance' => $balance, 'applied_points' => (int)$quote->getData('reward_points_used'), 'maximum' => $this->config->maxCheckoutPoints((int)$quote->getStoreId()), 'rate' => $this->config->redemptionRate((int)$quote->getStoreId())];
if (isset($result['drawer_totals'])) { $result['drawer_totals']['reward_discount'] = (float)$quote->getData('reward_discount_amount') > 0 ? '-' . $this->checkoutHelper->formatPrice((float)$quote->getData('reward_discount_amount')) : ''; }
return $result;
}
}