jQuery(document).ready(function($) { if(!ship_ajax.is_checkout) { // console.log("No es checkout"); return; } ship_ajax.cart_ready = false; populate("departaments"); $(document).on("change", ".form_group select", function() { // var child = $(this).parent().siblings("label").attr("class"); var child = $(this).find(":selected").data("child"); var sel_opt = $(this).find(":selected").val(); if(sel_opt == "0") return; if(child != "0") populate(child); else { var code = $(this).find(":selected").data("code"); notes_llenarPrimera(); getShippingRates(code); } }); $(document).on("click", ".shipping__method input", function() { var shipping_code = $(this).val(); // reset ship_ajax.cart_ready = false; jQuery('#id_select__day_name').val('0') jQuery('#box_shipping_hours').css('display', 'none') var note = ""; if(shipping_code != "PROGRAMMED") { ship_ajax.cart_ready = true; var shipping_method = jQuery("input[name='shipping_method[0]']:checked").val(); if((shipping_method && shipping_method.indexOf("local_pickup") == "-1") || !shipping_method) { note += "metodo_envio_codigo: " + $(this).val() + ";\n"; note += "gateway: " + $(this).data("gateway") + ";\n"; note += "programmed_date: " + "-;\n"; note += "programmed_time: " + "-;\n"; notes_llenarSegunda(note); } $(".programmed__group").hide(); $(".programmed_days__label").hide(); $(".programmed_days__select").prop("selectedIndex", 0); $(".programmed_days__select").hide(); setPricingMethodShipping() } else { // $(".programmed__group").show(); jQuery(".programmed__group").css('display', 'flex'); } }); // loaders // relay, relations - apolo $(document).on("click", ".btn_send_shipping_method", setPricingMethodShipping); $(document).on("change", "#container_option_pickup_stores .pickup_stores__item input", setPricingMethodShipping); function renderDateCustomShipping() { function diffBTWDays(date1, date2) { // To calculate the time difference of two dates var Difference_In_Time = date2.getTime() - date1.getTime(); // To calculate the no. of days between two dates var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24); //To display the final no. of days (result) return Difference_In_Days } function addDayDate(currentDate) { var newdate = new Date(currentDate); newdate.setDate(newdate.getDate() + 1); var dd = newdate.getDate(); var mm = newdate.getMonth() + 1; var yyyy = newdate.getFullYear(); return ({ dateparsed: `${mm}-${dd}-${yyyy}`, date: new Date(`${mm}/${dd}/${yyyy}`), dd, mm, yyyy }) } function getDayWeekParse(day) { switch(day) { case 0: return "sunday"; case 1: return "monday"; case 2: return "tuesday" case 3: return "wednesday" case 4: return "thursday" case 5: return "friday" case 6: return "saturday" } } function addZeroBefore(number) { return ('0' + number).slice(-2) } // what day is today var today = new Date() var daysWeekCollector = [] // define umbral days -> count from +2 days var umbralDays = 2 // Get the next 7 days available var nextDaysAvailables = 7 // max days requested //settings var weekDaysRules = { holidaysDates: [], weekdaysAvailables: { "monday" : true, "tuesday" : true, "wednesday": true, "thursday" : true, "friday" : true, "saturdays": false, "sunday" : false } } var currenDay = today var count = 0 // render scheadule list on available days while(daysWeekCollector.length < nextDaysAvailables && count < 90) { // ask for next day available // sumar +1 var nextDay = addDayDate(currenDay) currenDay = nextDay.date // ver diferencia de dias entre hoy y mañana var diffDaysFromToday = diffBTWDays(today, nextDay.date) var prettyDayName = getDayWeekParse(nextDay.date.getDay()) var isDayAvailable = prettyDayName && weekDaysRules.weekdaysAvailables[prettyDayName] var currentDateIsHoliday = weekDaysRules.holidaysDates.includes(`${addZeroBefore(nextDay.dd)}-${addZeroBefore(nextDay.mm)}`) // take care from umbral days from today if(diffDaysFromToday > umbralDays && isDayAvailable && !currentDateIsHoliday) { // insert element on list collector let formatDay = { "status": true, "day_name": prettyDayName, "day_number": nextDay.dd, "date": nextDay.dateparsed, "range_hours": [ { "range": "9-13", "status": true, "display": "9:00 a.m. - 1:00 p.m." }, { "range": "13-17", "status": true, "display": "1:00 p.m. - 5:00 p.m." }, { "range": "17-21", "status": true, "display": "5:00 p.m. - 9:00 p.m." } ] } daysWeekCollector.push(formatDay) } count++ } return daysWeekCollector } function setPricingMethodShipping(e) { var despachoSelected = jQuery("input[name=despacho]:checked").val(); var selectedShippingCode = jQuery(".shipping__method input:checked").val(); var selectedShippingPrice = jQuery(".shipping__method input:checked").data("price"); var selectedDistrictCode = jQuery('#billing_distrits').find('option:selected').data('code'); var selectedPickupStore = jQuery("input[name=despacho_pickup_option]:checked").data("name"); var canCalculateDelivery = despachoSelected === 'envio_domicilio' && selectedDistrictCode && selectedShippingCode && selectedShippingPrice !== undefined && selectedShippingPrice !== null && Number(selectedShippingPrice) >= 0; var canCalculatePickup = despachoSelected === 'recojo_tienda' && selectedPickupStore; // Delivery pricing does not depend on the street address; allow a shipping-method // click to update totals as soon as the district and method are selected. if(canCalculateDelivery || canCalculatePickup) { console.log('coding....') var shipping_code = $(".shipping__method input:checked").val(); var shipping_price = $(".shipping__method input:checked").data("price"); var despachoSelected = $("input[name=despacho]:checked").val() // validar desde aqui $(".woocommerce-NoticeGroup").hide(); var code_zipcode = jQuery('#billing_distrits').find('option:selected').data('code') var productCartURLParams = getQueryProductCartItemsData() var promiseSelected = null if(despachoSelected === 'recojo_tienda') { // var $storepickupselected = jQuery("input[name=despacho_pickup_option]:checked").val() var $storepickupselected = jQuery("input[name=despacho_pickup_option]:checked").data("name") promiseSelected = setShippingPricing('110000', $storepickupselected, 0, productCartURLParams, 'PICKUP_STORE') // render scheadule list if(e && e.target) { var customJSONinject = JSON.stringify(renderDateCustomShipping()) jQuery(e.target).parent().parent()[0].setAttribute('data-schedule', customJSONinject) } } else { promiseSelected = setShippingPricing(code_zipcode, shipping_code, shipping_price, productCartURLParams, 'DELIVERY') // obtengo todo los metodos de compra disponibles, se imprime, debería retornar } Promise.all([ promiseSelected ]).then(() => { jQuery("body").trigger("update_checkout"); }) .catch(() => { console.log('Error'); }) } } $(document).on("change", ".select__day_name", function() { ship_ajax.cart_ready = false; var date = $(this).find(":selected").val(); if(date == "0") return; $(".programmed_days__label").show(); $(".programmed_days__select").hide(); $("#programmed_days__select_" + date).show(); // jQuery('#programmed_days__select').val('0') // reset jQuery('#box_shipping_hours').html('') jQuery('#box_shipping_hours').css('display', 'block') // get days var daysStored = jQuery('#box_days_container').data('days') daysStored = typeof daysStored === 'string' ? JSON.parse(daysStored) : daysStored // get selected input console.log('date selected', date) // render input hours function renderInputHours(days, daySelected) { var findDay = days.find(day => day.date === daySelected) return (``) } var templateSelectInput = renderInputHours(daysStored, date) jQuery('#box_shipping_hours').html(templateSelectInput) jQuery('#box_shipping_hours').css('display', 'block') }); $(document).on("change", ".programmed_days__select", function() { var note = ""; var value = $(this).find(":selected").val(); if(value != "0") { ship_ajax.cart_ready = true; if(false) { note += "Tipo de envío: " + $(".shipping_methods__wrapper input[type='radio']:checked").next("span").html() + "; \n"; note += "Día escogido: " + $(".select__day_name :selected").html() + "; \n"; note += "Horario escogido: " + $(this).find(":selected").html(); } note = "metodo_envio_codigo: " + $(".shipping_methods__wrapper input[type='radio']:checked").val() + ";\n"; note += "gateway: " + $(".shipping_methods__wrapper input[type='radio']:checked").data("gateway") + ";\n"; note += "programmed_date: " + $(".select__day_name :selected").val() + ";\n"; note += "programmed_time: " + $(this).find(":selected").val() + ";\n"; notes_llenarSegunda(note); ship_ajax.cart_ready = true; setPricingMethodShipping() } }); $(document).ajaxStart($.blockUI).ajaxStop($.unblockUI); $(document).on("click", "#place_order", function(e) { e.preventDefault(); if(verify()) { $(".woocommerce-checkout").submit(); } else { customError("Debe completar el formulario de envío."); $(".woocommerce-NoticeGroup").show(); } }); $(document).on("click", "input[name='shipping_method[0]']", function() { var method = $(this).val(); if(method && method.indexOf("local_pickup") == -1) $(".woocommerce-additional-fields").show(); }); $("input[name='checkout_next_step']").click(function() { if($("#timeline-billing").hasClass("active") || $("#timeline-order").hasClass("active") ) { $(".btn_send_shipping_method").click(); console.log("se hizo clic al botoncito"); } }); /** * General extra */ function checkoutPaymentMovePosition () { var blockPaymen = jQuery("#payment") if(blockPaymen) jQuery("#customer_details").append(blockPaymen) } function addTittleBeforeShippingAddressForm() { // if(jQuery('#blockSecondStepTittle')) jQuery('#blockSecondStepTittle').remove() if(jQuery('#billing_country_field') && jQuery('#blockSecondStepTittle')) { var tittleblock = `
Paso 2 de 3 - Despacho

¿Cómo despachamos sus productos?

` jQuery(tittleblock).insertBefore('#billing_country_field'); } } function checkRegisterUserBlockPosition() { var isBlockInsideTarget = jQuery("#payment").find(".woocommerce-account-fields")[0] if(!isBlockInsideTarget) { // move backup // jQuery(jQuery(".woocommerce-account-fields:first")) // .style // .insertAfter('#payment') // set display none jQuery(".col-1 .woocommerce-account-fields").css("display", "none") // copy block on target zone var block_copy = jQuery(".woocommerce-account-fields:first").clone(true) jQuery(block_copy).insertBefore('.form-row.place-order') jQuery("#payment").find(".woocommerce-account-fields").css("display", "block") // console.log('execture!!') } else { console.log('NO execture!!') } } function collectionDespachoOptions() { function htmlObjectToString(stuff) { return stuff.outerHTML } /* Methods to render list despacho */ function printPickUpStoresList() { function renderStoreList(listStores) { // create list var elementContentListStores = document.createElement('div'); elementContentListStores.setAttribute('id', 'container_option_pickup_stores') elementContentListStores.setAttribute('class', 'pickup_stores__container') for(let store of listStores) { if(store.is_active) { elementContentListStores.innerHTML += ` ` } } // render jQuery("#container_option_despacho").after(elementContentListStores) jQuery("#container_option_pickup_stores").hide() jQuery("#container_option_pickup_stores").after("
") // jQuery("#container_option_pickup_stores").after("
") // set scheadule options - list jQuery(document).on('change', ".enova__input_stores_list_options", (ev) => { // get scheadule list var rawJSONscheadule = ev.currentTarget.parentNode.parentNode.getAttribute('data-schedule') var parseJSONscheadule = rawJSONscheadule !== '' ? JSON.parse(rawJSONscheadule) : null if(parseJSONscheadule) { // render on template jQuery('#enova_shop_store_scheadule_days').html(renderDaysToShopStores(parseJSONscheadule)) // ship_ajax.cart_ready = true; // setPricingMethodShipping() } else { // reset options pickup options jQuery('#id_shop_enova_pickupstore__select__day_name').val('0') jQuery('.pickupstore__programmed_days__select').val('0') // hide options jQuery('#enova_shop_store_scheadule_days__option').hide(); jQuery(".pickupstore__days__label").hide(); jQuery(".programmed_days__select").hide(); } }) // set scheadule options - days jQuery(document).on("change", ".shop_enova_pickupstore__select__day_name", function () { ship_ajax.cart_ready = false; var date = $(this).find(":selected").val(); if(date == "0") return; $(".pickupstore__days__label").show(); $(".programmed_days__select").hide(); $("#enova_shop_store_scheadule_hours__selected__" + date).show(); // jQuery('#programmed_days__select').val('0') // reset jQuery('#enova_shop_store_scheadule_hours').html('') jQuery('#enova_shop_store_scheadule_hours').css('display', 'block') // get days var daysStored = jQuery('#enova_shop_store_scheadule_days__option').data('days') daysStored = typeof daysStored === 'string' ? JSON.parse(daysStored) : daysStored // render input hours function renderInputHoursPickUpStore(days, daySelected) { var findDay = days.find(day => day.date === daySelected) return (``) } var templateSelectInput = renderInputHoursPickUpStore(daysStored, date) jQuery('#enova_shop_store_scheadule_hours').html(templateSelectInput) jQuery('#enova_shop_store_scheadule_hours').css('display', 'block') // save on notes var note_pick = "gateway: Pickup Store; \n"; note_pick += "programmed_date: " + jQuery(".shop_enova_pickupstore__select__day_name :selected").val() + "; \n"; note_pick += "programmed_time: " + jQuery(".pickupstore__programmed_days__select :selected").val() + "; \n"; notes_llenarSegunda(note_pick); ship_ajax.cart_ready = true; setPricingMethodShipping() }); // set scheadule options - hours jQuery(document).on("change", ".pickupstore__programmed_days__select", function () { // save on notes var note_pick = "gateway: Pickup Store; \n"; note_pick += "programmed_date: " + jQuery(".shop_enova_pickupstore__select__day_name :selected").val() + ";\n"; note_pick += "programmed_time: " + jQuery(".pickupstore__programmed_days__select :selected").val() + ";\n"; notes_llenarSegunda(note_pick); ship_ajax.cart_ready = true; setPricingMethodShipping() }); function prettyDay(day = null) { switch(day) { case 'monday': return 'Lunes' case 'tuesday': return 'Martes' case 'wednesday': return 'Miercoles' case 'thursday': return 'Jueves' case 'friday': return 'Viernes' case 'saturday': return 'Sabado' case 'sunday': return 'Domingo' default: return day } } function renderDaysToShopStores(dias = []) { return `
` } } function cleanDespachoOptions(target) { if(target === 'RECOJO_TIENDA') { jQuery("input[name=despacho_pickup_option]").attr('checked', false); // shipping methods hide jQuery("#updated_shipping_methods").show() // clean shipping jQuery("#updated_shipping_methods input[name=shipping__method]").attr('checked', false); } else if(target === 'SHIPPING') { // clean departamento jQuery("#billing_departaments_field").show() jQuery("#billing_departaments_field select").attr('value', null); // clean provinces jQuery("#billing_provinces_field").show() jQuery("#billing_provinces_field select").attr('value', null); // clean distritos jQuery("#billing_distrits_field").show() jQuery("#billing_distrits_field select").attr('value', null); // clean direcciones jQuery("#billing_address_1_field").show() jQuery("#billing_address_1_field select").attr('value', null); // shipping methods hide jQuery("#updated_shipping_methods").hide() // clean shipping jQuery("#updated_shipping_methods input[name=shipping__method]").attr('checked', false); } } function requestListStores() { jQuery.ajax({ "url": `${ship_ajax.host}company/shop-addresses/`, "headers": { "Authorization": "Token " + ship_ajax.comercio_token, "Content-Type": "application/json", }, "dataType": "json", success: function (result) { // var scheduleCustomSelected = renderDateCustomShipping() var scheduleCustomSelected = null var itemsStores = result && result.items ? result.items.map((item) => { return ({ ...item, schedule: item.schedule === 'true' ? scheduleCustomSelected : null }) }) : [] renderStoreList(itemsStores) }, error: function (err) { // reject(err) console.log('error al cargar las tiendas', err) } }); } // set list stores requestListStores() // events on input radio jQuery(".enova_despacho_shipping").on('change', (ev) => { var elementSelected = ev.currentTarget.value if(elementSelected === 'recojo_tienda') { // reset: shipping block cleanDespachoOptions('SHIPPING') // shipping block hide jQuery("#billing_departaments_field").hide() jQuery("#billing_provinces_field").hide() jQuery("#billing_distrits_field").hide() jQuery("#billing_address_1_field").hide() // recojo en tienda show jQuery("#container_option_pickup_stores").show() } else { // reset: recojo en tienda block cleanDespachoOptions('RECOJO_TIENDA') // shipping block show jQuery("#billing_departaments_field").show() jQuery("#billing_provinces_field").show() jQuery("#billing_distrits_field").show() jQuery("#billing_address_1_field").show() // recojo en tienda hide jQuery("#container_option_pickup_stores").hide() // reset options pickup options jQuery('#id_shop_enova_pickupstore__select__day_name').val('0') jQuery('.pickupstore__programmed_days__select').val('0') // hide options jQuery('#enova_shop_store_scheadule_days__option').hide(); jQuery(".pickupstore__days__label").hide(); jQuery(".programmed_days__select").hide(); } }) jQuery("#blockSecondStepTittle").after() } function printStoreDespachoOptions() { var elementContentDiv = document.createElement('div'); elementContentDiv.setAttribute('id', 'container_option_despacho') elementContentDiv.setAttribute('class', 'container_option_despacho_container') elementContentDiv.style.display = 'none' function validatePickStoreText() { var url = window.location.host switch(url) { case 'jch.enova.store': case 'www.jchllantas.com.pe': case 'jchllantas.com.pe': return 'Recojo en Tienda (Solo Lima)' default: return 'Recojo en Tienda' } } jQuery("#despacho_field input").each((index, item) => { // insert blocks var elementTemplate = (` `) elementContentDiv.innerHTML += elementTemplate; }) // delete input, label jQuery("#despacho_field").find('input').remove() jQuery("#despacho_field").find('label').remove() // render on html jQuery("#despacho_field").before(elementContentDiv) var insertBlockDespachoOptionsInterval = setInterval(() => { var blockStructure1 = jQuery("#container_option_despacho") var blockStructure2 = jQuery("#blockSecondStepTittle") if(blockStructure1 && blockStructure1[0] && blockStructure2 && blockStructure2[0] && blockStructure2[0].offsetParent) { jQuery("#container_option_despacho").appendTo( jQuery("#blockSecondStepTittle") ); jQuery("#container_option_despacho").css('display', 'flex') // trigger: select default radio input for default jQuery("#despacho_envio_domicilio").click() // clear interval clearInterval(insertBlockDespachoOptionsInterval) } }, 1000) } /* render */ printStoreDespachoOptions() printPickUpStoresList() } var blockIntervalTittle = setInterval(() => { if(!jQuery('#blockSecondStepTittle')[0]){ addTittleBeforeShippingAddressForm() } }, 200) setTimeout(() => { clearInterval(blockIntervalTittle) }, 6000) setInterval(() => { var isBlockInsideTarget = jQuery("#payment").find(".woocommerce-account-fields")[0] if(jQuery(".woocommerce-account-fields")) { if(!isBlockInsideTarget) { checkRegisterUserBlockPosition() } } }, 500) /** Set despacho collections */ var blockIntervalDespacho = setInterval(() => { var blockDespachoOption = jQuery("#despacho_envio_domicilio")[0] var blockDespacho2Insert = jQuery("#container_option_despacho")[0] var blockDespacho2Insert1 = jQuery("#blockSecondStepTittle")[0] var blockDespachoStep2 = jQuery("#blockSecondStepTittle")[0] if(blockDespachoOption && blockDespacho2Insert1 && !blockDespacho2Insert && blockDespachoStep2) { console.log('iteration start ----------') collectionDespachoOptions() console.log('iteration end ----------') } }, 1000) setTimeout(() => { clearInterval(blockIntervalDespacho) }, 5000) }); function verify() { console.log('error part 1') var shipping_method = jQuery("input[name='shipping_method[0]']:checked").val(); if(shipping_method && shipping_method.indexOf("local_pickup") != "-1") { jQuery(".woocommerce-additional-fields").hide(); return true; } console.log('error part 2') if(jQuery("input[name=despacho]:checked") && jQuery("input[name=despacho]:checked").val()) { console.log('error part 2/1') // validation var despachoOptionSelected = jQuery("input[name=despacho]:checked").val() if(despachoOptionSelected === 'envio_domicilio') { console.log('error part 2/2') var select_departament = jQuery("#billing_departaments_field select").val() var select_province = jQuery("#billing_provinces_field select").val() var select_district = jQuery("#billing_distrits_field select").val() var input_name = jQuery("#billing_address_1").val() var shipping_price_select = jQuery(".shipping__method input:checked").data("price"); if(select_departament && select_departament !== '' && select_province && select_province !== '' && select_district && select_district !== '' && input_name && input_name !== '' && shipping_price_select !== null && shipping_price_select !== undefined && Number(shipping_price_select) >= 0) { var shippping_method = jQuery(".shipping__method input:checked").val() var programmed_date = jQuery('#id_select__day_name').val() var programmed_hour = jQuery(".programmed_days__select").val() if(shippping_method && shippping_method === 'PROGRAMMED') { if(programmed_date === '0' || programmed_hour === '0') { console.log('la fecha no es correcta') return false } else { return true } } else { return true } } else { console.log('error part 2 - 1') return false } } else if(despachoOptionSelected === 'recojo_tienda') { console.log('error part 2/3') var select_pickup_store = jQuery("input[name=despacho_pickup_option]:checked").val() var select_pickup_store_day = jQuery('#id_shop_enova_pickupstore__select__day_name').val() var select_pickup_store_hour = jQuery('.pickupstore__programmed_days__select').val() if(select_pickup_store && select_pickup_store !== '') { console.log('error part 2/4') var isTermsAccepted = jQuery("#terms")[0].checked if(isTermsAccepted && ship_ajax.second_line && ship_ajax.second_line !== '') { if(select_pickup_store_day && select_pickup_store_day !== '0' && select_pickup_store_hour && select_pickup_store_hour !== '0') { return true } else { return false } } else { return true } } else { console.log('error part 2 - 2') return false } } else { console.log('error part 2 - 3') return false } } console.log('error por cart') return ship_ajax.cart_ready; } function customError(msg) { jQuery(function($) { var error_notice = $(".woocommerce-NoticeGroup"); if(error_notice.length == 0) $("form.woocommerce-checkout").prepend("
"); var error = ""; error += ""; $(".woocommerce-NoticeGroup").html(error); $([document.documentElement, document.body]).animate({ scrollTop: $(".woocommerce-error").offset().top - 180 }, 1000); }); } function populate(arg_child = "") { ship_ajax.cart_ready = false; // var opciones = ["countries", "departaments", "provinces", "distrits", "0"]; jQuery("#updated_shipping_methods").remove(); var opciones = ["departaments", "provinces", "distrits", "0"]; var host_params = ""; var child = "0"; var general_name = ""; for(var k = 0; k < opciones.length - 1; ++k) { if(opciones[k] == arg_child) { for(var x = k; x < opciones.length - 1; ++x) jQuery("#billing_" + opciones[x] + "").html(""); break; } } host_params += "countries/1/"; for(var j = 0; j < opciones.length - 1; ++j) { var current_select = jQuery("#billing_" + opciones[j]); // var current_name = current_select.attr("name"); current_name = opciones[j]; var current_options = current_select.find("option"); if(false) { console.log("Sobre los options: "); console.log(current_options); console.log(current_options.length); } if(current_options.length == 1) { // console.log("Solo hay un child en " + current_name); general_name = current_name; child = opciones[j + 1]; break; } var val_selected = current_select.find(":selected").val(); // ajax_data[current_name] = val_selected; host_params += current_name + "/" + val_selected + "/"; } host_params += general_name + "/"; if(false) { console.log("Token: " + ship_ajax.comercio_token); console.log("Host: " + ship_ajax.host); console.log("Token: " + ship_ajax.is_checkout); } jQuery.ajax({ url: ship_ajax.host + host_params, headers: { "Authorization": "Token " + ship_ajax.comercio_token, "Content-Type": "application/json", }, dataType: "json", // "data": ajax_data, "success": function(msg) { // console.log(msg); // console.log("General name: <" + general_name + ">"); var final = msg; var str = ""; var _code = ""; for(var i = 0; i < final.length; ++i) { _code = "data-code='" + ((final[i]["code"] == "")? "" : final[i]["code"]) + "'"; str += ""; } jQuery("#billing_" + general_name).append(str); } }); // var current_form_group = jQuery("#form_group_" + arr[i]); // if(current_form_group.length == 0) } function getQueryProductCartItemsData() { var weightList = jQuery('.enova_weight') if(!weightList.size()) return '' var productcart_arr = [] weightList.each((index, item) => { var itemDetail = { quantity: jQuery(item).data('quantity'), volumen_unit: jQuery(item).data('weight_volimen'), weight_unit: jQuery(item).data('weight'), position: jQuery(item).data('position') } var productParsedItemCart = { "quantity": itemDetail.quantity ? itemDetail.quantity : null, "volumen_unit": itemDetail.volumen_unit ? itemDetail.volumen_unit : null, "weight_unit": itemDetail.weight_unit ? itemDetail.weight_unit : null, "position": itemDetail.position ? itemDetail.position : null } productcart_arr.push(productParsedItemCart) }) // filter postiion duplicated elements var clean_productcart_arr = [] productcart_arr.forEach(item => { let isExist = clean_productcart_arr.find(el => Number(item.position) === Number(el.position)) if(!isExist) clean_productcart_arr.push(item) }) return clean_productcart_arr } function getShippingRates(code) { ship_ajax.cart_ready = false; var productCartURLParams_string = getQueryProductCartItemsData() var url_request = `${ ship_ajax.host }shipping-methods/?ubigeo=${ code }${ productCartURLParams_string ? `&products=${JSON.stringify(productCartURLParams_string)}` : '' }` jQuery.ajax({ // "url": ship_ajax.ajax_url, "url": url_request, "headers": { "Authorization": "Token " + ship_ajax.comercio_token, "Content-Type": "application/json", }, "dataType": "json", "data": { "action": "shipp_rates", "ubi": code }, success: function(msg) { jQuery("#updated_shipping_methods").remove(); var div_prueba = jQuery(".woocommerce-additional-fields__field-wrapper"); var div_prueba2 = jQuery(".woocommerce-additional-fields"); if(div_prueba.length) { // alert("1"); // jQuery("

Opciones de envío

").insertAfter(".woocommerce-additional-fields__field-wrapper"); jQuery("

Opciones de envío

").insertAfter("#billing_address_1"); } else if(div_prueba2.length) { // alert("2"); jQuery(".woocommerce-additional-fields").html("

Opciones de envío

"); } else { // alert("3"); // jQuery("#customer_billing_details").append("

Opciones de envío

"); // jQuery("

Opciones de envío

").insertAfter(".woocommerce-billing-fields"); jQuery("

Opciones de envío

").insertAfter("#billing_address_1"); } var opciones = "
"; opciones += "
" opciones += "
"; // console.log("Mensaje: "); // console.log(msg); // var datos = JSON.parse(msg); var datos = msg function prettyDay(day = null) { switch(day) { case 'monday': return 'Lunes' case 'tuesday': return 'Martes' case 'wednesday': return 'Miercoles' case 'thursday': return 'Jueves' case 'friday': return 'Viernes' case 'saturday': return 'Sabado' case 'sunday': return 'Domingo' default: return day } } // function calculatePricing(ship_ajax, datos) { // switch(datos[i]["shipping_price"]) { // case 0: // return 'envio gratis' // default: // return `${ ship_ajax.currency_symbol } ${ datos[i]["shipping_price"] && typeof datos[i]["shipping_price"] === 'number' // ? datos[i]["shipping_price"].toFixed(2) // : datos[i]["shipping_price"] }` // } // } function calculatePricing(ship_ajax, datos) { function renderDefaultMessage(ship_ajax, datos) { return ` ${ ship_ajax.currency_symbol } ${ datos[i]["shipping_price"] && typeof datos[i]["shipping_price"] === 'number' ? datos[i]["shipping_price"].toFixed(2) : datos[i]["shipping_price"] }` } // freeshipping by ubigeos list - mode var cart_subtotal_mib_mount = ship_ajax.free_shipping_by_ubigeo_cart_min_mount ? ship_ajax.free_shipping_by_ubigeo_cart_min_mount : null var cart_subtotal = jQuery(".cart-subtotal .woocommerce-Price-amount").text() ? jQuery(".cart-subtotal .woocommerce-Price-amount").text().replace('S/', '') : null var ubigeoSelected = jQuery("#billing_distrits").find(":selected").data("code") ? jQuery("#billing_distrits").find(":selected").data("code") : null if(ship_ajax.is_free_shipping_by_ubigeo_list && ship_ajax.is_free_shipping_by_ubigeo_list === "SI") { var listUbigeoFreeShippingSelected = ship_ajax.free_shipping_by_ubigeo_list ? ship_ajax.free_shipping_by_ubigeo_list : null var listUbigeoFreeShippingSelectedArray = listUbigeoFreeShippingSelected.split(',') var isUbigeoFreeShippingSelectedArray = listUbigeoFreeShippingSelectedArray.includes(String(ubigeoSelected)) if (isUbigeoFreeShippingSelectedArray && cart_subtotal_mib_mount && Number(cart_subtotal) >= Number(cart_subtotal_mib_mount)) { return '- envio gratis' } else { return renderDefaultMessage(ship_ajax, datos) } // freeshipping by ubigeos list - mode } else if (ship_ajax.is_free_shipping_by_weight_zero && ship_ajax.is_free_shipping_by_weight_zero === "SI") { function isAllProductCartWeightZero () { var savedproductCARTListFreeShippingWeightZero = getQueryProductCartItemsData() var isAllCartProductWeightZero = false; console.log('array ->', savedproductCARTListFreeShippingWeightZero) if(!Array.isArray(savedproductCARTListFreeShippingWeightZero)) { isAllCartProductWeightZero = true; } else { isAllCartProductWeightZero = true; for(cart_product of savedproductCARTListFreeShippingWeightZero ) { var productItemWeight = Number(cart_product['weight_unit']); if (productItemWeight && productItemWeight > 0) { isAllCartProductWeightZero = false; break; } } } return isAllCartProductWeightZero } if (isAllProductCartWeightZero()) { return '- envio gratis' } else { return renderDefaultMessage(ship_ajax, datos) } } else if (ship_ajax.is_pricing_by_range_weight && ship_ajax.is_pricing_by_range_weight === "SI") { var listShippingPricesRangeAll = ship_ajax.pricing_by_range_weight_list // 150116;0-3:8,4-6:10,7-10:15|150140;0-3:8,4-6:10,7-10:15 var cleanListShippingPricesRangesAll = listShippingPricesRangeAll.split('|') // ['150116;0-3:8,4-6:10,7-10:15','150140;0-3:8,4-6:10,7-10:15']; // find ubigeo on list var shippingPriceUbigeoValueSelected = null; var shippingPriceUbigeoRangeSelected = null; for(cart_productItemUbigeo of cleanListShippingPricesRangesAll) { var cleanListShippingPricesRangesUbigeoOptions = cart_productItemUbigeo.split(';'); // ['150116','0-3:8,4-6:10,7-10:15']; var shippingPriceUbigeoFirstValue = cleanListShippingPricesRangesUbigeoOptions[0]; var shippingPriceUbigeoSecondValue = cleanListShippingPricesRangesUbigeoOptions[1]; if(String(ubigeoSelected) === shippingPriceUbigeoFirstValue) { var shippingPriceUbigeoValueSelected = shippingPriceUbigeoFirstValue; var shippingPriceUbigeoRangeSelected = shippingPriceUbigeoSecondValue; break; } } console.log('shippingPriceUbigeoValueSelected', shippingPriceUbigeoValueSelected) console.log('shippingPriceUbigeoRangeSelected', shippingPriceUbigeoRangeSelected) if(shippingPriceUbigeoValueSelected && shippingPriceUbigeoRangeSelected) { // arrays option range list // var listShippingPricesRange = ship_ajax.pricing_by_range_weight_list // 0-3:8,4-6:10,7-10:15 var listShippingPricesRange = shippingPriceUbigeoRangeSelected // 0-3:8,4-6:10,7-10:15 var cleanListShippingPricesRanges = listShippingPricesRange.split(',') // ['0-3:8','4-6:10','7-10:15']; // bloque var total_cart_weight = 0; var shippingRange_price = datos[i]['shipping_price']; var isRangeInLimitRange = false; // obtener actual total sumado de pesos -> set "cart total weight" var savedproductCARTListToRangePrices = getQueryProductCartItemsData() if(!Array.isArray(savedproductCARTListToRangePrices)) { total_cart_weight = 0 } else { total_cart_weight = 0 for (cart_productItem of savedproductCARTListToRangePrices) { var productItemRangeWeight = cart_productItem['weight_unit']; var productItemRangeQuantity = cart_productItem['quantity']; var productItemRangeTotalWeight = productItemRangeWeight * productItemRangeQuantity; total_cart_weight += productItemRangeTotalWeight; } } // if doesn't have weight, set default, take the first element if(total_cart_weight === 0) { var rangePriceItemVariables = cleanListShippingPricesRanges[0] ? cleanListShippingPricesRanges[0].split(':') : [] // get variables split ":" get -> rango [0] , price[1] var item_price = rangePriceItemVariables[1]; shippingRange_price = item_price; } else { // find if "cart total weight" match on list range for (rangePriceItem of cleanListShippingPricesRanges) { var rangePriceItemVariables = rangePriceItem.split(':'); // get variables split ":" get -> rango [0] , price[1] var item_range_weight = rangePriceItemVariables[0]; var item_price = rangePriceItemVariables[1]; var item_range_weight_raw = item_range_weight.split('-') var item_range_weight_rangeA = item_range_weight_raw[0]; var item_range_weight_rangeB = item_range_weight_raw[1]; // if "$total_cart_weight" match on range -> rango [0] -> then set price[1] if(total_cart_weight >= item_range_weight_rangeA && total_cart_weight <= item_range_weight_rangeB) { shippingRange_price = item_price; isRangeInLimitRange = true; break; } } // if break up the limit in list will take the last element if(!isRangeInLimitRange) { var blockSelected = cleanListShippingPricesRanges[cleanListShippingPricesRanges.length - 1]; var rangePriceItemVariables = blockSelected.split(':') // get variables split ":" get -> rango [0] , price[1] var item_price = rangePriceItemVariables[1]; shippingRange_price = item_price; } } datos[i]['shipping_price'] = Number(shippingRange_price); console.log('PRICING -', shippingRange_price) console.log('total_cart_weight -', total_cart_weight) if(!shippingRange_price || Number(shippingRange_price) === 0) { // clementine validation if(total_cart_weight > 5) { return '- costo a coordinar' } else { return '- envio gratis' } } else { return renderDefaultMessage(ship_ajax, datos) } } else { return renderDefaultMessage(ship_ajax, datos) } } else { switch(datos[i]["shipping_price"]) { case 0: return '- envio gratis' default: return renderDefaultMessage(ship_ajax, datos) } } } function getPricingText(ship_ajax, datos, shipping_method_code) { switch(shipping_method_code) { case 'CUSTOM': return ` ${datos[i]["shipping_method_name"]}` default: return ` ${datos[i]["shipping_method_name"]} ${ ship_ajax.is_pricing_active === 'SI' ? calculatePricing(ship_ajax, datos) : '' }` } } for(var i = 0; i < datos.length; ++i) { opciones += ` ` function renderDays(dias = []) { return `
` } } opciones += "
"; opciones += "
Continuar
"; opciones += "
"; jQuery("#updated_shipping_methods").append(opciones); // jQuery(".programmed__group").hide(); jQuery(".programmed__group").hide(); jQuery(".programmed_days__label").hide(); jQuery(".programmed_days__select").hide(); // The first Enova rate is the checkout default. Trigger its handler explicitly; // inserting a checked radio does not emit a user click/change event. var $enovaRates = jQuery("#updated_shipping_methods .shipping__method input[name='shipping__method']"); if($enovaRates.length) { $enovaRates.first().prop("checked", true).trigger("click"); } var checcc = jQuery("input[name='shipping_method[0]']:checked"); if(checcc.length) { var shipping_method = jQuery("input[name='shipping_method[0]']:checked").val(); if(shipping_method.indexOf("local_pickup") != "-1") jQuery(".woocommerce-additional-fields").hide(); } // jQuery("body").trigger("update_checkout"); } }); } function setShippingPricing(code, method, price, productCartURLParams, despacho) { function cleanShippingPricingToZero() { var $mainblockShipping = jQuery("#shipping_method #shipping_method_0_flat_rate1").parent().find('label') if($mainblockShipping) { var $mainblockShippingAmount = jQuery("#shipping_method #shipping_method_0_flat_rate1").parent().find('label .woocommerce-Price-amount') if($mainblockShippingAmount) { $mainblockShippingAmount.remove() } var templatePricing = `: S/0.00` $mainblockShipping.append(templatePricing) } } return new Promise((resolve, reject) => { // ship_ajax.cart_ready = false; jQuery.ajax({ "url": ship_ajax.ajax_url, "method": "GET", "data": { action: "shipp_rates", ubi: code, lacartprod: JSON.stringify(productCartURLParams), shipping_method: method, price: price, primera_linea: ship_ajax.first_line, segunda_linea: ship_ajax.second_line, despacho: despacho }, success: () => { resolve(true) if(price === 0) { setTimeout(() => { cleanShippingPricingToZero() }, 1500) } }, error: (err) => { reject(err) } }); }) } function shippingMethod(method, price) { console.log('re: event') jQuery.ajax({ "url": ship_ajax.ajax_url, "data": { "action": "shipp_method", "shipping_method": method, }, success: function(msg) { jQuery("body").trigger("update_checkout"); // refresh_shipping_rate(); } }); } function refresh_shipping_rate() { if(ship_ajax.cart_ready) { jQuery("body").trigger("update_checkout"); } } function save_data() { // alert(ship_ajax.first_line); // alert(ship_ajax.second_line); jQuery.ajax({ "url": ship_ajax.ajax_url, "data": { "action": "save_note", "primera_linea": ship_ajax.first_line, "segunda_linea": ship_ajax.second_line, }, success: function(msg) {} }); return "OK"; } function notes_llenarPrimera() { var note = ""; note += "departamento: " + jQuery("#billing_departaments").find(":selected").html() + "; \n"; note += "provincia: " + jQuery("#billing_provinces").find(":selected").html() + "; \n"; note += "distrito: " + jQuery("#billing_distrits").find(":selected").html() + "; \n"; note += "ubigeo: " + jQuery("#billing_distrits").find(":selected").data("code") + "; \n"; ship_ajax.first_line = note; } function notes_llenarSegunda(note) { ship_ajax.second_line = note; // console.log("Segunda línea llenada: " + ship_ajax.second_line); } No pudimos encontrar la página que buscas - Aqualight
Bienvenidos a nuestra nueva web

La página que estas buscando no esta disponible
Pruebe buscando otro termino o haga click en el botón para regresar a la tienda

Volver

Cerrar

Ingresar