class SaleItemModal { constructor() { this.$modal = $("#sale-item-modal"); this.modal = bootstrap.Modal.getInstance(this.$modal.get(0)); this.$modal.on("show.bs.modal", event => this.onShow(event)); this.$modal.on("shown.bs.modal", () => this.onShown()); this.$modal.on("hidden.bs.modal", () => this.onHidden()); this.$title = this.$modal.find(".modal-title"); this.$form = this.$modal.find("form"); this.$form.on("submit", event => this.onSubmit(event)); this.form = this.$form.get(0); this.$saleItemIdField = this.getField("sale_item_id"); this.$supplierDropdown = this.getField("supplier_id"); this.$supplierDropdown.on("change", () => this.onSupplierChange()); this.$productDropdown = this.getField("product_id"); this.$productDropdown.on("change", event => this.onProductChange()); this.$quantityField = this.getField("quantity"); this.$unitPriceField = this.getField("unit_price"); } getField(name) { return this.$form.find(`[name=${name}]`); } // Modal lifecycle onShow(event) { const $element = $(event.relatedTarget); const data = $element.data(); const { saleNumber, supplierId, item } = data; if(!saleNumber) { console.error("saleNumber not provided."); return false; } this.saleNumber = data.saleNumber; if(item) { this.$title.text("Update Lead Item"); this.$saleItemIdField.val(item.id); this.$supplierDropdown.val(supplierId); this.onSupplierChange().then(() => { this.$productDropdown.val(item.productId); }); this.$quantityField.val(item.quantity); this.$unitPriceField.val(item.unitPrice); } else { this.$title.text("Add Lead Item"); } } onSupplierChange() { const supplierId = this.$supplierDropdown.val(); this.clearProducts(); const deferred = $.Deferred(); if(!supplierId) { deferred.resolve(); return deferred; } return $.get(`/suppliers/${supplierId}/get-products`).then(response => { const options = response.products.map(product => { const option = document.createElement("option"); option.textContent = product.name; option.value = product.id; option.dataset.price = product.price; option.hidden = product.archived; return option; }); this.$productDropdown.append(options); }).catch(error => { if(error.responseJSON && error.responseJSON.message) { toastr.error(error.responseJSON.message); } }); } clearProducts() { this.$productDropdown.find("option[value!='']").remove(); } onProductChange() { const $option = this.$productDropdown.find("option:selected"); this.$unitPriceField.val($option.data("price")); } onShown() { this.$supplierDropdown.trigger("focus"); } onHidden() { this.$form.get(0).reset(); this.$saleItemIdField.val(null); this.clearProducts(); } onSubmit(event) { event.preventDefault(); $.post(`/leads/${this.saleNumber}/submit-item`, this.$form.serialize()).then(response => { this.$modal.modal("hide"); $("#sale-items-section").html(response.html); toastr.success("Item saved successfully."); SalePage.InitSaleItemSection(); }); } } $(() => new SaleItemModal());