sutty-base-jekyll-theme/_packs/controllers/cart_coupon_controller.js

82 lines
2 KiB
JavaScript
Raw Permalink Normal View History

2021-11-22 17:51:50 +00:00
import { CartBaseController } from "./cart_base_controller";
2021-10-27 19:16:14 +00:00
/*
* Retrieves shipping methods
*/
export default class extends CartBaseController {
2021-11-22 17:51:50 +00:00
static targets = ["couponCodeInvalid", "preDiscount", "total"];
2021-10-27 19:16:14 +00:00
2021-11-22 17:51:50 +00:00
connect() {
this.input_event = this._input_event.bind(this);
this.couponCode.addEventListener("input", this.input_event);
}
disconnect() {
this.couponCode.removeEventListener("input", this.input_event);
}
_input_event(event) {
this.couponCode.parentElement.classList.remove("was-validated");
this.couponCode.setCustomValidity("");
2021-10-27 19:16:14 +00:00
}
2021-11-22 17:51:50 +00:00
get couponCode() {
if (!this._couponCode) this._couponCode = this.element.elements.coupon_code;
2021-10-27 19:16:14 +00:00
2021-11-22 17:51:50 +00:00
return this._couponCode;
2021-10-27 19:16:14 +00:00
}
2021-11-22 17:51:50 +00:00
get couponCodeInvalid() {
return this.hasCouponCodeInvalidTarget
? this.couponCodeInvalidTarget
: document.querySelector("#coupon-code-invalid");
2021-10-27 19:16:14 +00:00
}
2021-11-22 17:51:50 +00:00
get preDiscount() {
return this.hasPreDiscountTarget
? this.preDiscountTarget
: document.querySelector("#pre-discount");
2021-10-27 19:16:14 +00:00
}
2021-11-22 17:51:50 +00:00
get total() {
return this.hasTotalTarget
? this.totalTarget
: document.querySelector("#total");
2021-10-27 19:16:14 +00:00
}
2021-11-22 17:51:50 +00:00
set total(total) {
this.total.innerHTML = total;
2021-10-27 19:16:14 +00:00
}
2021-11-22 17:51:50 +00:00
async apply(event = undefined) {
event?.preventDefault();
event?.stopPropagation();
2021-10-27 19:16:14 +00:00
2021-11-22 17:51:50 +00:00
const orderToken = this.token;
const coupon_code = this.couponCode.value;
const include = "line_items";
2021-10-27 19:16:14 +00:00
2021-11-22 17:51:50 +00:00
const response = await window.spree.cart.applyCouponCode(
{ orderToken },
{ coupon_code, include }
);
2021-10-27 19:16:14 +00:00
2021-11-22 17:51:50 +00:00
this.element.elements.forEach((x) => (x.disabled = true));
2021-10-27 19:16:14 +00:00
if (response.isFail()) {
2021-11-22 17:51:50 +00:00
this.couponCodeInvalid.innerHTML = response.fail().summary;
this.couponCode.setCustomValidity(response.fail().summary);
this.couponCode.parentElement.classList.add("was-validated");
2021-10-27 19:16:14 +00:00
2021-11-22 17:51:50 +00:00
this.element.elements.forEach((x) => (x.disabled = false));
2021-10-27 19:16:14 +00:00
2021-11-22 17:51:50 +00:00
return;
2021-10-27 19:16:14 +00:00
}
2021-11-22 17:51:50 +00:00
this.cart = response;
this.total = response.success().data.attributes.total;
this.preDiscount.classList.remove("d-none");
2021-10-27 19:16:14 +00:00
}
}