Working of discount coupons on the checkout page in Magento 2.2.2 - How does the total_segments add or remove "discount"?

I am trying to understand the working of discount coupon codes on the checkout page.

When we apply any coupon code, then the discount is added without reloading the page.

I checked and found some below points:

  • discount” totals segment is added by Magento_SalesRule module.

When we apply any coupon code then, using vendor\magento\module-sales-rule\view\frontend\web\js\action\set-coupon-code.js, an ajax request is send to rest/default/V1/carts/mine/coupons/:coupon.

Code from 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);
        });
  • After the above ajax call, Summary total section gets refresh and
    Discount appears in it [ Attached image].

  • When we click on the cancel coupon button then code from
    vendor\magento\module-sales-rule\view\frontend\web\js\action\cancel-coupon.js
    runs and “Discount” disappears from the summary total section.

How does the total_segments add or remove “discount”?