Работа купонов на скидку на странице оформления заказа в Magento 2.2.2


Я пытаюсь понять, как работают коды купонов на скидку на странице оформления заказа.

Когда мы применяем любой код купона, скидка добавляется в корзину без перезагрузки страницы.

Я проверил и нашел некоторые пункты ниже:

  • " скидка"сегмент итогов добавляется модулем magento_salesrule.

Когда мы применяем любой код купона, затем, используя vendor\magento\module-sales-rule\view\frontend\web\js\action\set-coupon-code.js, запрос ajax отправляется на rest/default/V1/carts/mine/coupons/:coupon.

Код из vendor\magento\module-sales-rule\view\frontend\web\js\action\set-coupon-code.js :

 return storage.put(
            url,
            {},
            false
        ).done(function (response) {
            var deferred;

            if (response) {
                deferred = $.Deferred();

                isApplied(true);
                totals.isLoading(true);
                getPaymentInformationAction(deferred);
                $.when(deferred).done(function () 
                {
                    fullScreenLoader.stopLoader();
                    totals.isLoading(false);
                });
                messageContainer.addSuccessMessage({
                    'message': message
                });
            }
        }).fail(function (response) {
            fullScreenLoader.stopLoader();
            totals.isLoading(false);
            errorProcessor.process(response, messageContainer);
        });
  • После вышеупомянутого вызова ajax раздел "Итоговая сумма" обновляется и Скидка отображается в нем под изображением.

apply coupon

  • Когда мы нажимаем на кнопку отменить купон, затем вводим код из vendor\magento\module-sales-rule\view\frontend\web\js\action\cancel-coupon.js запускается, и "Скидка" исчезает из раздела итоговая сумма.

enter image description here

Как total_segments добавляет или удаляет "скидку"?

1 answers

1) Для учетной записи клиента: /V1/carts/mine/coupons/:couponCode

Я просто объясняю, как работают правила продажи для зарегистрированных клиентов

А) Установить купон:

vendor/magento/module-quote/etc/webapi.xml

<route url="/V1/carts/mine/coupons/:couponCode" method="PUT">
    <service class="Magento\Quote\Api\CouponManagementInterface" method="set"/>
    <resources>
        <resource ref="Magento_Cart::manage" />
    </resources>
</route>

Таким образом, будет использоваться класс интерфейса класса обслуживания Magento\Quote\Api\CouponManagementInterface::set() и будет вызван Magento\Quote\Model\CouponManagement::set.

$quote->setCouponCode($couponCode);
$this->quoteRepository->save($quote->collectTotals());

Когда котировка собирает итоговые данные: $quote->collectTotals()

\Magento\SalesRule\Model\Quote\Discount::collect() будет вызван. Он рассчитает логику купона здесь.

Б) Удалить купон:

vendor/magento/module-quote/etc/webapi.xml

<route url="/V1/carts/mine/coupons" method="DELETE">
    <service class="Magento\Quote\Api\CouponManagementInterface" method="remove"/>
    <resources>
        <resource ref="self" />
    </resources>
    <data>
        <parameter name="cartId" force="true">%cart_id%</parameter>
    </data>
</route>

Magento\Quote\Model\CouponManagement::remove() будет вызван.

C) Общий сегмент: V1/carts/mine/payment-information

vendor/magento/module-checkout/etc/webapi.xml

<route url="/V1/carts/mine/payment-information" method="GET">
    <service class="Magento\Checkout\Api\PaymentInformationManagementInterface" method="getPaymentInformation"/>
    <resources>
        <resource ref="self" />
    </resources>
    <data>
        <parameter name="cartId" force="true">%cart_id%</parameter>
    </data>
</route>

vendor/magento/module-checkout/Model/PaymentInformationManagement.php

/**
 * {@inheritDoc}
 */
public function getPaymentInformation($cartId)
{
    ...
    $paymentDetails->setTotals($this->cartTotalsRepository->get($cartId));
    ...
}

\ Magento\Цитата\Модель\Корзина\Carttotalрепозиция::получить()

 if ($quote->isVirtual()) {
        $addressTotalsData = $quote->getBillingAddress()->getData();
        $addressTotals = $quote->getBillingAddress()->getTotals();
    } else {
        $addressTotalsData = $quote->getShippingAddress()->getData();
        $addressTotals = $quote->getShippingAddress()->getTotals();
    }
......

$calculatedTotals = $this->totalsConverter->process($addressTotals);
$quoteTotals->setTotalSegments($calculatedTotals);

Это позволит получить итоговые данные и установить всего сегментов.

\Magento\Quote\Model\Quote\TotalsReader::fetch()

foreach ($this->collectorList->getCollectors($quote->getStoreId()) as $reader) {
        $data = $reader->fetch($quote, $total);

2) Для гостевой учетной записи мы можем увидеть API-интерфейсы:

vendor/magento/module-quote/etc/webapi.xml

<!-- Managing Guest Cart Coupons -->
<route url="/V1/guest-carts/:cartId/coupons" method="GET">
    <service class="Magento\Quote\Api\GuestCouponManagementInterface" method="get"/>
    <resources>
        <resource ref="anonymous" />
    </resources>
</route>
<route url="/V1/guest-carts/:cartId/coupons/:couponCode" method="PUT">
    <service class="Magento\Quote\Api\GuestCouponManagementInterface" method="set"/>
    <resources>
        <resource ref="anonymous" />
    </resources>
</route>
<route url="/V1/guest-carts/:cartId/coupons" method="DELETE">
    <service class="Magento\Quote\Api\GuestCouponManagementInterface" method="remove"/>
    <resources>
        <resource ref="anonymous" />
    </resources>
</route>
 6
Author: Khoa TruongDinh, 2018-04-20 01:49:15