define([ 'jquery', 'Esun_Cart/js/model/coupon-service' ], function ($, couponService) { 'use strict'; return function (config, element) { var $page = $(element), submitTimer; $page.on('click', '[data-esun-qty-change]', function () { var $button = $(this), $input = $button.siblings('[data-role="cart-item-qty"]'), currentQty = parseFloat($input.val()) || 1, difference = parseFloat($button.attr('data-esun-qty-change')) || 0, nextQty = Math.max(1, currentQty + difference); if (nextQty === currentQty) { return; } $input.val(nextQty).trigger('change'); window.clearTimeout(submitTimer); submitTimer = window.setTimeout(function () { $page.find('.action.update').trigger('click'); }, 350); }); $page.on('submit', '[data-role="esun-coupon-form"]', function (event) { event.preventDefault(); saveCoupon($(this), false); }); $page.on('click', '[data-role="esun-coupon-form"] .esun-coupon__remove', function (event) { event.preventDefault(); saveCoupon($(this).closest('form'), true); }); $(document).on('esun:customerCouponApplied.esunCartPage', function () { window.location.reload(); }); function saveCoupon($form, remove) { var $message = $form.find('[data-role="esun-coupon-message"]'), $buttons = $form.find('button'), couponCode = $.trim($form.find('[name="coupon_code"]').val() || ''); if ($form.data('loading')) { return; } if (!remove && !couponCode) { $message .removeClass('is-success') .addClass('is-error') .text($.mage.__('Please enter a coupon code.')); return; } $form.data('loading', true).addClass('is-loading'); $buttons.prop('disabled', true); $message.removeClass('is-success is-error').empty(); (remove ? couponService.remove() : couponService.apply(couponCode)).done(function (response) { if (response && response.success) { window.location.reload(); return; } $message .addClass('is-error') .text(response && response.message ? response.message : $.mage.__('We could not update the coupon code.')); }).fail(function (xhr) { var response = xhr.responseJSON || {}; $message .addClass('is-error') .text(response.message || $.mage.__('We could not update the coupon code. Please try again.')); }).always(function () { $form.data('loading', false).removeClass('is-loading'); $buttons.prop('disabled', false); }); } }; });