Search

Sep 28, 2023

Magento 2: get discount, gift card amount, subtotal, grand total

<?php
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\GiftCardAccount\Api\GiftCardAccountManagementInterface;
use Magento\GiftCardAccount\Api\Data\GiftCardAccountInterface;

class Price {
  /** @var CheckoutSession */
  protected $checkoutSession;

  /** @var GiftCardAccountManagementInterface */
  private $giftCardAccountManagementInterface;

  public function __construct(
    CheckoutSession                    $checkoutSession,
    GiftCardAccountManagementInterface $giftCardAccountManagementInterface
  )
  {
    $this->checkoutSession = $checkoutSession;
    $this->giftCardAccountManagementInterface = $giftCardAccountManagementInterface;
  }


  public function execute()
  {
    $quote = $this->getCurrentQuote();

    if ($quote) {
      $shippingAddress = $quote->getShippingAddress();
      $subTotal = round((float) $quote->getSubtotal(), 2);
      $grandTotal = round((float) $quote->getGrandTotal(), 2);
      $taxAmount = round((float) $shippingAddress->getTaxAmount(), 2);
      $giftCardAmountAvailableTotal = round((float) $quote->getGiftCardsAmount(), 2);

      // Get giftcard used
      $giftCardAccount = $this->getGiftCardAccount();
      $giftCardUsedAmount = $giftCardAccount->getGiftCardsAmountUsed();
      $giftCardAmount = round($giftCardUsedAmount, 2);

      // Get discount
      $items = $quote->getAllItems();
      $discountAmount = 0;
      foreach ($items as $item) {
        $discountAmount += $item->getDiscountAmount();
      }
      $discountAmount = round((float) $discountAmount, 2);

    }
  }


  /**
   * @param $quoteId
   * @return GiftCardAccountInterface
   */
  protected function getGiftCardAccount($quoteId = null)
  {
    if (!$quoteId) {
      $quoteId = $this->getCurrentQuote()->getId();
    }
    return $this->giftCardAccountManagementInterface->getListByQuoteId($quoteId);
  }

  /**
   * @return CartInterface|Quote
   */
  public function getCurrentQuote()
  {
    return $this->checkoutSession->getQuote();
  }

}

No comments:

Post a Comment