class NewDocumentModal { constructor() { this.$modal = $("#new-document-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.$ticketIdField = this.getField("ticket_id"); this.$companyDropdown = this.getField("company_id"); this.$locationDropdown = this.getField("location_id"); this.$supplierDropdown = this.getField("supplier_id"); this.$supplierFormGroup = this.$supplierDropdown.closest(".mb-3"); this.$aruSection = $("#new-document-aru-section"); this.$itemDescriptionField = this.getField("item_description"); this.$itemSerialNumberField = this.getField("item_serial_number"); this.$productLookupDropdown = $("#new-document-product-lookup"); this.$productLookupDropdown.select2({ theme: "bootstrap-5", dropdownParent: this.$modal }); this.$productLookupDropdown.on("change", () => { const $option = this.$productLookupDropdown.find("option:selected"); this.$itemDescriptionField.val($option.data("name")); }); this.$locationDropdown.select2({ theme: "bootstrap-5", dropdownParent: this.$locationDropdown.closest("div") }); const parameters = new URLSearchParams(window.location.search); const locationId = parameters.get("add_location_id"); if(locationId) { const button = document.getElementById("new-document-button"); button.click(); } } getField(name) { return this.$form.find(`[name=${name}]`); } // Modal lifecycle onShow(event) { const $element = $(event.relatedTarget); const data = $element.data(); const { type, locationId, ticketId } = data; this.$supplierFormGroup.show(); this.$aruSection.show(); switch(type) { case DocumentTypes.SalesOrder: this.$title.text("New Sales Order"); this.baseUrl = "/sales-orders"; this.$aruSection.hide(); this.$supplierFormGroup.hide(); break; case DocumentTypes.GoodsIn: this.$title.text("New Goods-In"); this.baseUrl = "/goods-in"; this.$aruSection.hide(); break; case DocumentTypes.AdvancedReplacementUnit: this.$title.text("New ARU"); this.baseUrl = "/arus"; this.$supplierFormGroup.hide(); break; } if(locationId) { this.$locationDropdown.val(locationId); } if(ticketId) { this.$ticketIdField.val(ticketId); } } onShown() { this.$companyDropdown.trigger("focus"); } onHidden() { this.$form.get(0).reset(); this.$ticketIdField.val(null); } onSubmit(event) { event.preventDefault(); const data = this.$form.serialize(); $.post(`${this.baseUrl}/create`, data).then(response => { this.$modal.modal("hide"); window.location = response.url; }).catch(error => { console.log(error); }); } } $(() => new NewDocumentModal());