1 line
19 KiB
JavaScript
Executable File
1 line
19 KiB
JavaScript
Executable File
"use strict";App.Pages.Booking=function(){function detectDatepickerMonthChangeStep(previousDateTimeMoment,nextDateTimeMoment){return previousDateTimeMoment.isAfter(nextDateTimeMoment)?-1:1}function prefillFromQueryParam(field,param){var $target=$(field);$target.length&&$target.val(App.Utils.Url.queryParam(param))}function optimizeContactInfoDisplay(){var $firstCol=$("#wizard-frame-3 .field-col:first"),$firstColControls=$firstCol.find(".form-control"),$secondCol=$("#wizard-frame-3 .field-col:last"),$secondColControls=$secondCol.find(".form-control");1===$firstColControls.length&&1<$secondColControls.length&&$firstColControls.each(function(index,controlEl){$(controlEl).parent().insertBefore($secondColControls.first().parent())}),1===$secondColControls.length&&1<$firstColControls.length&&$secondColControls.each(function(index,controlEl){$(controlEl).parent().insertAfter($firstColControls.last().parent())});var $fieldCols=$(document).find("#wizard-frame-3 .field-col");$fieldCols.each(function(index,fieldColEl){var $fieldCol=$(fieldColEl);$fieldCol.find(".form-control").length||$fieldCol.hide()})}function addEventListeners(){$selectTimezone.on("change",function(){var date=App.Utils.UI.getDateTimePickerValue($selectDate);date&&(App.Http.Booking.getAvailableHours(moment(date).format("YYYY-MM-DD")),App.Pages.Booking.updateConfirmFrame())}),$selectProvider.on("change",function(event){var $target=$(event.target),todayDateTimeObject=new Date,todayDateTimeMoment=moment(todayDateTimeObject);App.Utils.UI.setDateTimePickerValue($selectDate,todayDateTimeObject),App.Http.Booking.getUnavailableDates($target.val(),$selectService.val(),todayDateTimeMoment.format("YYYY-MM-DD")),App.Pages.Booking.updateConfirmFrame()}),$selectService.on("change",function(event){var $target=$(event.target),serviceId=$selectService.val();$selectProvider.empty(),$selectProvider.append(new Option(lang("please_select_service"),"")),vars("available_providers").forEach(function(provider){var canServeService=0<provider.services.filter(function(providerServiceId){return+providerServiceId===+serviceId}).length;canServeService&&$selectProvider.append(new Option(provider.first_name+" "+provider.last_name,provider.id))}),1<$selectProvider.find("option").length&&"1"===vars("display_any_provider")&&$(new Option(lang("any_provider"),"any-provider")).insertAfter($selectProvider.find("option:first")),App.Http.Booking.getUnavailableDates($selectProvider.val(),$target.val(),moment(App.Utils.UI.getDateTimePickerValue($selectDate)).format("YYYY-MM-DD")),App.Pages.Booking.updateConfirmFrame(),App.Pages.Booking.updateServiceDescription(serviceId)}),$(".button-next").on("click",function(event){var $target=$(event.currentTarget);if("1"!==$target.attr("data-step_index")||$selectProvider.val()){if("2"===$target.attr("data-step_index")&&!$(".selected-hour").length)return void($("#select-hour-prompt").length||$("<div/>",{id:"select-hour-prompt",class:"text-danger mb-4",text:lang("appointment_hour_missing")}).prependTo("#available-hours"));if("3"===$target.attr("data-step_index")){if(!App.Pages.Booking.validateCustomerForm())return;App.Pages.Booking.updateConfirmFrame()}var nextTabIndex=parseInt($target.attr("data-step_index"))+1;$target.parents().eq(1).fadeOut(function(){$(".active-step").removeClass("active-step"),$("#step-"+nextTabIndex).addClass("active-step"),$("#wizard-frame-"+nextTabIndex).fadeIn()});var scrollingElement=document.scrollingElement||document.body;window.innerHeight<scrollingElement.scrollHeight&&(scrollingElement.scrollTop=0)}}),$(".button-back").on("click",function(event){var prevTabIndex=parseInt($(event.currentTarget).attr("data-step_index"))-1;$(event.currentTarget).parents().eq(1).fadeOut(function(){$(".active-step").removeClass("active-step"),$("#step-"+prevTabIndex).addClass("active-step"),$("#wizard-frame-"+prevTabIndex).fadeIn()})}),$availableHours.on("click",".available-hour",function(event){$availableHours.find(".selected-hour").removeClass("selected-hour"),$(event.target).addClass("selected-hour"),App.Pages.Booking.updateConfirmFrame()}),manageMode&&($("#cancel-appointment").on("click",function(){var $cancellationReason,$cancelAppointmentForm=$("#cancel-appointment-form"),buttons=[{text:lang("close"),click:function click(event,messageModal){messageModal.hide()}},{text:lang("confirm"),click:function click(){return""===$cancellationReason.val()?void $cancellationReason.css("border","2px solid #DC3545"):void($cancelAppointmentForm.find("#hidden-cancellation-reason").val($cancellationReason.val()),$cancelAppointmentForm.submit())}}];return App.Utils.Message.show(lang("cancel_appointment_title"),lang("write_appointment_removal_reason"),buttons),$cancellationReason=$("<textarea/>",{class:"form-control",id:"cancellation-reason",rows:"3",css:{width:"100%"}}).appendTo("#message-modal .modal-body"),!1}),$deletePersonalInformation.on("click",function(){var buttons=[{text:lang("cancel"),click:function click(event,messageModal){messageModal.hide()}},{text:lang("delete"),click:function click(){App.Http.Booking.deletePersonalInformation(vars("customer_token"))}}];App.Utils.Message.show(lang("delete_personal_information"),lang("delete_personal_information_prompt"),buttons)})),$bookAppointmentSubmit.on("click",function(){var $acceptToTermsAndConditions=$("#accept-to-terms-and-conditions");if($acceptToTermsAndConditions.removeClass("is-invalid"),$acceptToTermsAndConditions.length&&!$acceptToTermsAndConditions.prop("checked"))return void $acceptToTermsAndConditions.addClass("is-invalid");var $acceptToPrivacyPolicy=$("#accept-to-privacy-policy");return $acceptToPrivacyPolicy.removeClass("is-invalid"),$acceptToPrivacyPolicy.length&&!$acceptToPrivacyPolicy.prop("checked")?void $acceptToPrivacyPolicy.addClass("is-invalid"):void App.Http.Booking.registerAppointment()}),$captchaTitle.on("click","button",function(){$(".captcha-image").attr("src",App.Utils.Url.siteUrl("captcha?"+Date.now()))}),$selectDate.on("mousedown",".ui-datepicker-calendar td",function(){setTimeout(function(){App.Http.Booking.applyPreviousUnavailableDates()},300)})}function updateConfirmFrame(){var serviceOptionText=$selectService.find("option:selected").text();$(".display-selected-service").text(serviceOptionText).removeClass("invisible");var providerOptionText=$selectProvider.find("option:selected").text();if($(".display-selected-provider").text(providerOptionText).removeClass("invisible"),!!$availableHours.find(".selected-hour").text()){var serviceId=$selectService.val(),service=vars("available_services").find(function(availableService){return+availableService.id===+serviceId});if(service){var formattedSelectedDate,selectedDateObject=App.Utils.UI.getDateTimePickerValue($selectDate),selectedDateMoment=moment(selectedDateObject),selectedDate=selectedDateMoment.format("YYYY-MM-DD"),selectedTime=$availableHours.find(".selected-hour").text(),selectedDateTime="".concat(selectedDate," ").concat(selectedTime);selectedDateObject&&(formattedSelectedDate=App.Utils.Date.format(selectedDateTime,vars("date_format"),vars("time_format"),!0));var timezoneOptionText=$selectTimezone.find("option:selected").text();$("#appointment-details").html("\n <div>\n <div class=\"mb-2 fw-bold fs-3\">\n ".concat(serviceOptionText,"\n </div> \n <div class=\"mb-2 fw-bold text-muted\">\n ").concat(providerOptionText,"\n </div>\n <div class=\"mb-2\">\n <i class=\"fas fa-calendar-day me-2\"></i>\n ").concat(formattedSelectedDate,"\n </div> \n <div class=\"mb-2\">\n <i class=\"fas fa-clock me-2\"></i>\n ").concat(service.duration," ").concat(lang("minutes"),"\n </div>\n <div class=\"mb-2\">\n <i class=\"fas fa-globe me-2\"></i>\n ").concat(timezoneOptionText,"\n </div> \n <div class=\"mb-2\" ").concat(+service.price?"":"hidden",">\n <i class=\"fas fa-cash-register me-2\"></i>\n ").concat((+service.price).toFixed(2)," ").concat(service.currency,"\n </div>\n </div> \n "));var firstName=App.Utils.String.escapeHtml($firstName.val()),lastName=App.Utils.String.escapeHtml($lastName.val()),fullName="".concat(firstName," ").concat(lastName).trim(),email=App.Utils.String.escapeHtml($email.val()),phoneNumber=App.Utils.String.escapeHtml($phoneNumber.val()),address=App.Utils.String.escapeHtml($address.val()),city=App.Utils.String.escapeHtml($city.val()),zipCode=App.Utils.String.escapeHtml($zipCode.val()),addressParts=[];city&&addressParts.push(city),zipCode&&addressParts.push(zipCode),$("#customer-details").html("\n <div>\n <div class=\"mb-2 fw-bold fs-3\">\n ".concat(lang("contact_info"),"\n </div>\n <div class=\"mb-2 fw-bold text-muted\" ").concat(fullName?"":"hidden",">\n ").concat(fullName,"\n </div>\n <div class=\"mb-2\" ").concat(email?"":"hidden",">\n ").concat(email,"\n </div>\n <div class=\"mb-2\" ").concat(email?"":"hidden",">\n ").concat(phoneNumber,"\n </div>\n <div class=\"mb-2\" ").concat(address?"":"hidden",">\n ").concat(address,"\n </div>\n <div class=\"mb-2\" ").concat(addressParts.length?"":"hidden",">\n ").concat(addressParts.join(", "),"\n </div>\n </div>\n "));var data={};data.customer={last_name:$lastName.val(),first_name:$firstName.val(),email:$email.val(),phone_number:$phoneNumber.val(),address:$address.val(),city:$city.val(),zip_code:$zipCode.val(),timezone:$selectTimezone.val(),custom_field_1:$customField1.val(),custom_field_2:$customField2.val(),custom_field_3:$customField3.val(),custom_field_4:$customField4.val(),custom_field_5:$customField5.val()},data.appointment={start_datetime:moment(App.Utils.UI.getDateTimePickerValue($selectDate)).format("YYYY-MM-DD")+" "+moment($(".selected-hour").data("value"),"HH:mm").format("HH:mm")+":00",end_datetime:calculateEndDatetime(),notes:$notes.val(),is_unavailability:!1,id_users_provider:$selectProvider.val(),id_services:$selectService.val()},data.manage_mode=+manageMode,manageMode&&(data.appointment.id=vars("appointment_data").id,data.customer.id=vars("customer_data").id),$("input[name=\"post_data\"]").val(JSON.stringify(data))}}}function calculateEndDatetime(){var endMoment,serviceId=$selectService.val(),service=vars("available_services").find(function(availableService){return+availableService.id===+serviceId}),selectedDate=moment(App.Utils.UI.getDateTimePickerValue($selectDate)).format("YYYY-MM-DD"),selectedHour=$(".selected-hour").data("value"),startMoment=moment(selectedDate+" "+selectedHour);return endMoment=service.duration&&startMoment?startMoment.clone().add({minutes:parseInt(service.duration)}):moment(),endMoment.format("YYYY-MM-DD HH:mm:ss")}function applyAppointmentData(appointment,provider,customer){try{$selectService.val(appointment.id_services).trigger("change"),$selectProvider.val(appointment.id_users_provider);var startMoment=moment(appointment.start_datetime);App.Utils.UI.setDateTimePickerValue($selectDate,startMoment.toDate()),App.Http.Booking.getAvailableHours(startMoment.format("YYYY-MM-DD")),$lastName.val(customer.last_name),$firstName.val(customer.first_name),$email.val(customer.email),$phoneNumber.val(customer.phone_number),$address.val(customer.address),$city.val(customer.city),$zipCode.val(customer.zip_code),customer.timezone&&$selectTimezone.val(customer.timezone);var appointmentNotes=null===appointment.notes?"":appointment.notes;return $notes.val(appointmentNotes),$customField1.val(customer.custom_field_1),$customField2.val(customer.custom_field_2),$customField3.val(customer.custom_field_3),$customField4.val(customer.custom_field_4),$customField5.val(customer.custom_field_5),App.Pages.Booking.updateConfirmFrame(),!0}catch(exc){return!1}}var $selectDate=$("#select-date"),$selectService=$("#select-service"),$selectProvider=$("#select-provider"),$selectTimezone=$("#select-timezone"),$firstName=$("#first-name"),$lastName=$("#last-name"),$email=$("#email"),$phoneNumber=$("#phone-number"),$address=$("#address"),$city=$("#city"),$zipCode=$("#zip-code"),$notes=$("#notes"),$captchaTitle=$(".captcha-title"),$availableHours=$("#available-hours"),$bookAppointmentSubmit=$("#book-appointment-submit"),$deletePersonalInformation=$("#delete-personal-information"),$customField1=$("#custom-field-1"),$customField2=$("#custom-field-2"),$customField3=$("#custom-field-3"),$customField4=$("#custom-field-4"),$customField5=$("#custom-field-5"),tippy=window.tippy,moment=window.moment,manageMode=vars("manage_mode")||!1;return document.addEventListener("DOMContentLoaded",function initialize(){var _window;if(!!+vars("display_cookie_notice")&&null!==(_window=window)&&void 0!==_window&&_window.cookieconsent){cookieconsent.initialise({palette:{popup:{background:"#ffffffbd",text:"#666666"},button:{background:"#429a82",text:"#ffffff"}},content:{message:lang("website_using_cookies_to_ensure_best_experience"),dismiss:"OK"}});var $cookieNoticeLink=$(".cc-link");$cookieNoticeLink.replaceWith($("<a/>",{"data-bs-toggle":"modal","data-bs-target":"#cookie-notice-modal",href:"#",class:"cc-link",text:$cookieNoticeLink.text()}))}manageMode=vars("manage_mode"),tippy("[data-tippy-content]");var monthTimeout;App.Utils.UI.initializeDatePicker($selectDate,{inline:!0,minDate:moment().subtract(1,"day").set({hours:23,minutes:59,seconds:59}).toDate(),maxDate:moment().add(vars("future_booking_limit"),"days").toDate(),onChange:function onChange(selectedDates){App.Http.Booking.getAvailableHours(moment(selectedDates[0]).format("YYYY-MM-DD")),App.Pages.Booking.updateConfirmFrame()},onMonthChange:function onMonthChange(selectedDates,dateStr,instance){$selectDate.parent().fadeTo(400,.3),monthTimeout&&clearTimeout(monthTimeout),monthTimeout=setTimeout(function(){var previousMoment=moment(instance.selectedDates[0]),displayedMonthMoment=moment(instance.currentYearElement.value+"-"+(+instance.monthsDropdownContainer.value+1+"").padStart(2,"0")+"-01"),monthChangeStep=detectDatepickerMonthChangeStep(previousMoment,displayedMonthMoment);App.Http.Booking.getUnavailableDates($selectProvider.val(),$selectService.val(),displayedMonthMoment.format("YYYY-MM-DD"),monthChangeStep)},500)},onYearChange:function onYearChange(selectedDates,dateStr,instance){setTimeout(function(){var previousMoment=moment(instance.selectedDates[0]),displayedMonthMoment=moment(instance.currentYearElement.value+"-"+(+instance.monthsDropdownContainer.value+1)+"-01"),monthChangeStep=detectDatepickerMonthChangeStep(previousMoment,displayedMonthMoment);App.Http.Booking.getUnavailableDates($selectProvider.val(),$selectService.val(),displayedMonthMoment.format("YYYY-MM-DD"),monthChangeStep)},500)}}),App.Utils.UI.setDateTimePickerValue($selectDate,new Date);var browserTimezone=Intl.DateTimeFormat().resolvedOptions().timeZone,isTimezoneSupported=0<$selectTimezone.find("option[value=\"".concat(browserTimezone,"\"]")).length;if($selectTimezone.val(isTimezoneSupported?browserTimezone:"UTC"),addEventListeners(),optimizeContactInfoDisplay(),manageMode)applyAppointmentData(vars("appointment_data"),vars("provider_data"),vars("customer_data")),$("#wizard-frame-1").css({visibility:"visible",display:"none"}).fadeIn();else{var selectedServiceId=App.Utils.Url.queryParam("service");selectedServiceId&&0<$selectService.find("option[value=\""+selectedServiceId+"\"]").length&&$selectService.val(selectedServiceId),$selectService.trigger("change");var selectedProviderId=App.Utils.Url.queryParam("provider");if(selectedProviderId&&0===$selectProvider.find("option[value=\""+selectedProviderId+"\"]").length)for(var index in vars("available_providers")){var provider=vars("available_providers")[index];provider.id===selectedProviderId&&0<provider.services.length&&$selectService.val(provider.services[0]).trigger("change")}selectedProviderId&&0<$selectProvider.find("option[value=\""+selectedProviderId+"\"]").length&&$selectProvider.val(selectedProviderId).trigger("change"),selectedServiceId&&selectedProviderId||1===vars("available_services").length&&1===vars("available_providers").length?(!selectedServiceId&&$selectService.val(vars("available_services")[0].id).trigger("change"),!selectedProviderId&&$selectProvider.val(vars("available_providers")[0].id).trigger("change"),$(".active-step").removeClass("active-step"),$("#step-2").addClass("active-step"),$("#wizard-frame-1").hide(),$("#wizard-frame-2").fadeIn(),$selectService.closest(".wizard-frame").find(".button-next").trigger("click"),$(document).find(".book-step:first").hide(),$(document).find(".button-back:first").css("visibility","hidden"),$(document).find(".book-step:not(:first)").each(function(index,bookStepEl){return $(bookStepEl).find("strong").text(index+1)})):$("#wizard-frame-1").css({visibility:"visible",display:"none"}).fadeIn(),prefillFromQueryParam("#first-name","first_name"),prefillFromQueryParam("#last-name","last_name"),prefillFromQueryParam("#email","email"),prefillFromQueryParam("#phone-number","phone"),prefillFromQueryParam("#address","address"),prefillFromQueryParam("#city","city"),prefillFromQueryParam("#zip-code","zip")}}),{manageMode:manageMode,updateConfirmFrame:updateConfirmFrame,updateServiceDescription:function updateServiceDescription(serviceId){var _service$description,$serviceDescription=$("#service-description");$serviceDescription.empty();var service=vars("available_services").find(function(availableService){return+availableService.id===+serviceId});if(service){var additionalInfoParts=[];if(service.duration&&additionalInfoParts.push("".concat(lang("duration"),": ").concat(service.duration," ").concat(lang("minutes"))),0<+service.price&&additionalInfoParts.push("".concat(lang("price"),": ").concat((+service.price).toFixed(2)," ").concat(service.currency)),service.location&&additionalInfoParts.push("".concat(lang("location"),": ").concat(service.location)),additionalInfoParts.length&&$("\n <div class=\"mb-2 fst-italic\">\n ".concat(additionalInfoParts.join(", "),"\n </div>\n ")).appendTo($serviceDescription),null!==(_service$description=service.description)&&void 0!==_service$description&&_service$description.length){var escapedDescription=App.Utils.String.escapeHtml(service.description),multiLineDescription=escapedDescription.replaceAll("\n","<br/>");$("\n <div class=\"text-muted\">\n ".concat(multiLineDescription,"\n </div>\n ")).appendTo($serviceDescription)}}},validateCustomerForm:function validateCustomerForm(){$("#wizard-frame-3 .is-invalid").removeClass("is-invalid"),$("#wizard-frame-3 label.text-danger").removeClass("text-danger");var missingRequiredField=!1;if($(".required").each(function(index,requiredField){$(requiredField).val()||($(requiredField).addClass("is-invalid"),missingRequiredField=!0)}),missingRequiredField)return $("#form-message").text(lang("fields_are_required")),!1;if($email.val()&&!App.Utils.Validation.email($email.val()))return $email.addClass("is-invalid"),$("#form-message").text(lang("invalid_email")),!1;var phoneNumber=$phoneNumber.val();return!phoneNumber||App.Utils.Validation.phone(phoneNumber)||($phoneNumber.addClass("is-invalid"),$("#form-message").text(lang("invalid_phone")),!1)}}}(); |