diff --git a/_data/layouts/payment.yml b/_data/layouts/payment.yml index 2fd1705..da9c652 100644 --- a/_data/layouts/payment.yml +++ b/_data/layouts/payment.yml @@ -60,6 +60,18 @@ special_instructions_help: default: es: 'Horas específicas de entrega, etc.' en: 'Specific delivery hours, etc.' +promo_code: + type: 'string' + required: true + label: + es: 'Código de descuento' + en: 'Coupon code' + help: + es: '' + en: '' + default: + es: '¿Tenés un cupón de descuento?' + en: '' permalink: type: 'permalink' required: true diff --git a/_packs/controllers/cart_coupon_controller.js b/_packs/controllers/cart_coupon_controller.js new file mode 100644 index 0000000..15edb3d --- /dev/null +++ b/_packs/controllers/cart_coupon_controller.js @@ -0,0 +1,64 @@ +import { CartBaseController } from './cart_base_controller' + +/* + * Retrieves shipping methods + */ +export default class extends CartBaseController { + static targets = [ 'couponCodeInvalid', 'preDiscount', 'total' ] + + connect () { + this.couponCode.addEventListener('input', event => { + this.couponCode.parentElement.classList.remove('was-validated') + this.couponCode.setCustomValidity('') + }) + } + + get couponCode () { + if (!this._couponCode) this._couponCode = this.element.elements.coupon_code + + return this._couponCode + } + + get couponCodeInvalid () { + return this.hasCouponCodeInvalidTarget ? this.couponCodeInvalidTarget : document.querySelector('#coupon-code-invalid') + } + + get preDiscount () { + return this.hasPreDiscountTarget ? this.preDiscountTarget : document.querySelector('#pre-discount') + } + + get total () { + return this.hasTotalTarget ? this.totalTarget : document.querySelector('#total') + } + + set total (total) { + this.total.innerHTML = total + } + + async apply (event = undefined) { + event?.preventDefault() + event?.stopPropagation() + + const orderToken = this.token + const coupon_code = this.couponCode.value + const include = 'line_items' + + const response = await window.spree.cart.applyCouponCode({ orderToken }, { coupon_code, include }) + + this.element.elements.forEach(x => x.disabled = true) + + if (response.isFail()) { + this.couponCodeInvalid.innerHTML = response.fail().summary + this.couponCode.setCustomValidity(response.fail().summary) + this.couponCode.parentElement.classList.add('was-validated') + + this.element.elements.forEach(x => x.disabled = false) + + return + } + + this.cart = response + this.total = response.success().data.attributes.total + this.preDiscount.classList.remove('d-none') + } +} diff --git a/assets/templates/payment_methods.html b/assets/templates/payment_methods.html index d294a7a..322eceb 100644 --- a/assets/templates/payment_methods.html +++ b/assets/templates/payment_methods.html @@ -1,3 +1,5 @@ +
+