Votre panier

Votre panier est vide!
Envoyez vos références par Email

Envoyez vos références par Email

Envoyer

Envoyez vos références par WhatsApp

Envoyer     
\n\n"}, "collapsed": false, "template_id": 30, "template_name": "HTML", "display_design": false}] //home page if(this.sections){ this.setSectionData(this.sections) } //search else if (page_type == 'search'){ this.searchProducts() } //cart else if(page_type == 'cart'){ let params = new URLSearchParams(window.location.search); if(this.cart._details.length < 1 && !params.has('quick-cart')){ alert('Le panier est vide') } } //account else if (page_type == 'account') { this.logged ? this.getCustomerOrders() : window.location = "/account/login" } //product-list else if(page_type == 'product_group'){ this.category = ""; let queryString = window.location.search; let urlParams = new URLSearchParams(queryString); this.productsSize = 20; let page = urlParams.get('page') ? urlParams.get('page') : 1 this.getFilterParams(); this.initializeFiltersFromURL(); } //product else if (page_type == 'product' ){ this.product = ""; //set default product selected if(this.product.declinaisons.length && this.product.declinaisons.findIndex(x=>x.default) != -1){ setTimeout(()=>{ let selectedProduct = this.product.declinaisons.find(x=>x.default); for(let attr of selectedProduct._attributs){ this.filterSubProduct(attr['productoption'], attr['id']); } },100) }else { this.products_filtered = this.product.declinaisons.length ? this.product.declinaisons : [this.product]; } this.buildAttributs(); //call api products this.getProductFrequentlyboughtTogether(); //call product } //whishlist else if (page_type == 'wishlist'){ this.logged ? this.getWishlistProducts() : window.location.href = "/" } }, getLocalstorageOrDefault(item){ let data = localStorage.getItem(item); if(data){ this.packProductCart = JSON.parse(data); } }, isLoggedin(){ this.token = localStorage.getItem('_token') return this.token ? true : false }, /**************************** END INIT ****************************/ /**************************** CART ****************************/ addToPackThisProduct(product,component_id, $event){ $event.preventDefault(); if (product) { this.temp_cart[component_id].push(product); localStorage.setItem('temp_cart', JSON.stringify(this.temp_cart)) $('.dialog-pack').hide(); $('body').removeClass('modal-open'); } }, tempCartChoice(product_ids){ this.cart._details = []; setTimeout(()=>{ products = this.sectionData['offers'].filter(x => product_ids.find(id => id === x.id) !== undefined) for(let product of products){ this.addProductToCartObj(product, 1); } },1) }, getQuantityOfCartGroup(group_id){ try { return this.packProductCart[group_id].map(x=>x.quantity).reduce((a, b) => a + b) } catch{ return 0; } }, updateQuanity(product_id, group_id, action=1, max, $event){ if(this.getQuantityOfCartGroup(group_id) < max || action == -1){ let index = this.packProductCart[group_id].findIndex(x=>x.id == product_id); this.packProductCart[group_id][index]['quantity'] += action; if(this.packProductCart[group_id][index]['quantity'] == 0){ this.packProductCart[group_id].splice(index,1) } localStorage.setItem('pack_product_cart', JSON.stringify(this.packProductCart)) } }, addBasicPackToCart(group_id, max){ //FACEBOOK PIXEL if(this.getQuantityOfCartGroup(group_id) == max){ this.has_pixel && fbq('track', 'AddToCart', { content_ids: [group_id], content_type: "product_group", value:(this.product.price ), currency: "TND", }, { eventID : this.event_id } ); this.sendEventFacebookConversion('AddToCart', {details:group_id, price:(this.cart['total'] )}) let options = []; for(let detail of this.packProductCart[group_id]){ options.push({ product_name : detail.product.name, quantity : detail.quantity, product_id : detail.id, photo_thumb:detail.photo_thumb }) } this.addProductToCartObj(this.product, 1, options); this.packProductCart[group_id] = []; $('.dialog-pack').hide(); $('body').removeClass('modal-open'); $('.cart-dropdown a').trigger('click'); } }, addPackToCart(group_id, max){ console.log(this.packProductCart, group_id, '+++++') if(this.checkIfPackIsFilled(this.packProductCart[group_id])){ //FACEBOOK PIXEL this.has_pixel && fbq('track', 'AddToCart', { content_ids: [group_id], content_type: "product_group", value:(this.product.price ), currency: "TND", }, { eventID : this.event_id } ); this.sendEventFacebookConversion('AddToCart', {details:group_id, price:(this.cart['total'] )}) let options = []; for(let detail of this.packProductCart[group_id]){ options.push({ product_name : detail.product.name, quantity : detail.quantity, product_id : detail.id, photo_thumb: detail.photo_thumb, attrs : detail.attrs }) } this.addProductToCartObj(this.product, 1, options); this.packProductCart[group_id] = []; localStorage.setItem('pack_product_cart', JSON.stringify(this.packProductCart)) $('.select2').val('').trigger('change') $('.dialog-pack').hide(); $('body').removeClass('modal-open'); $('.cart-dropdown a').trigger('click'); } }, checkIfPackIsFilled(array){ for (let i = 0; i < array.length; i++) { if (array[i] == '') { alert('Veuillez séléctionner le produit '+this.packProducts[i].name) return false } } return true; // Return -1 if no null elements are found }, addToPackProductGroup(product, group_id, quantity, $event){ $event.preventDefault(); //create array if doesnt exist if(this.packProductCart[group_id] == undefined){ this.packProductCart[group_id] = []; } //add product to array if doesnt exist if(this.getQuantityOfCartGroup(group_id) < this.product.stock){ if(this.packProductCart[group_id].findIndex(x=>x.id == product.id) == -1){ this.packProductCart[group_id].push({product, quantity, id : product.id, photo_thumb:product.photo_thumb }); } //modify quantity else { let index = this.packProductCart[group_id].findIndex(x=>x.id == product.id) this.packProductCart[group_id][index]['quantity'] = quantity; } } localStorage.setItem('pack_product_cart', JSON.stringify(this.packProductCart)) }, IfProductInPack(product, group_id){ if(this.packProductCart[group_id]){ return this.packProductCart[group_id].findIndex(x=>x.id == product.id) != -1; } return false; }, ProductInPack(product, group_id){ if(this.packProductCart[group_id]){ return this.packProductCart[group_id].find(x=>x.id == product.id); } }, removeFromTempCart(index, component_id){ this.temp_cart[component_id].splice(index,1); localStorage.setItem('temp_cart', JSON.stringify(this.temp_cart)); }, addTempToCart(component_id, $event){ for(product of this.temp_cart[component_id]){ //FACEBOOK PIXEL this.has_pixel && fbq('track', 'AddToCart', { content_ids: [product.parent ? product.parent : product.id], content_type: "product_group", value: product.price, currency: "TND", }, { eventID : this.event_id } ); this.sendEventFacebookConversion('AddToCart', {details:[product.parent ? product.parent : product.id], price:(product.price )}) this.addProductToCartObj(product, 1); $('.dialog-pack').hide(); $('body').removeClass('modal-open'); } this.setPromoCodeValue(); $('.cart-dropdown a').trigger('click'); }, addToCartThisProduct(quantity=1, $event, product, checkout=false, opencart=true){ $event.preventDefault(); if (product) { //FACEBOOK PIXEL this.has_pixel && fbq('track', 'AddToCart', { content_ids: [product.parent ? product.parent : product.id], content_type: "product_group", value: product.price * quantity, currency: "TND", }, { eventID : this.event_id } ); this.sendEventFacebookConversion('AddToCart', {details:[product.parent ? product.parent : product.id], price:(product.price * quantity )}) //ADD TO CART OBJ this.addProductToCartObj(product, quantity); this.setPromoCodeValue(); $('.dialog-pack').hide(); $('body').removeClass('modal-open'); checkout && (window.location.href = "/checkout"); !checkout && opencart && $('.cart-toggle').trigger('click'); } }, expressCheckout(event){ let product = this.products_filtered[0]; if (this.checkIfProductSelected() || this.products_filtered.length == 1) { //FACEBOOK PIXEL AddToCart event let __price = this.getPriceOfProduct(product, this.productQte); this.has_pixel && fbq('track', 'AddToCart', { content_ids: [product.parent ? product.parent : product.id], content_type: "product_group", value: __price, currency: "TND", }, { eventID : this.event_id } ); this.sendEventFacebookConversion('AddToCart', {details:[product.parent ? product.parent : product.id], price:(__price )}) //check stock if(this.stock_settings.display_stock_onwebsite && (product.active_stock && product.stock < this.productQte)){ this.productInfo.title = "Stock épuisé" this.productInfo.message = "Produit en rupture de stock"; return $('#add-to-cart-modal').modal(); } this.cart._details = []; this.addProductToCartObj(product, this.productQte); let product_ids = this.cart._details.map(x=>x.product_id) this.setPromoCodeValue() $('#checkout-dialog').modal(); } else { let emptyOptions = []; for (let option_id in this.filterForm) { if (this.filterForm[option_id] == "") { emptyOptions.push(this.pOptions.find(x => x.id == option_id)); } } alert("Veuillez choisir :" + emptyOptions.map(x => x.name).join(', ')); return false; } }, addToCart(quantity=1, event, checkout=false, displayModal=true) { event.preventDefault(); //FIND PRODUCT let product = this.products_filtered[0]; if (this.checkIfProductSelected() || this.products_filtered.length == 1) { //FACEBOOK PIXEL let __price = this.getPriceOfProduct(product, quantity) this.has_pixel && fbq('track', 'AddToCart', { content_ids: [product.parent ? product.parent : product.id], content_type: "product_group", value: (__price ), currency: "TND", }, { eventID : this.event_id } ); this.sendEventFacebookConversion('AddToCart', {details:[product.parent ? product.parent : product.id], price:(__price )}) //ANIMATION SHAKE ON CART $('.cart, .mobile-cart').addClass('onshake'); setTimeout(()=>{$('.cart, .mobile-cart').removeClass('onshake')},4000); //check stock if(this.stock_settings.display_stock_onwebsite && (product.active_stock && product.stock < quantity)){ this.productInfo.title = "Stock épuisé" this.productInfo.message = "Produit en rupture de stock"; $('.cart-toggle').trigger('click'); return true } //check if product is already in cart let productExist = this.cart._details.find(p => p._product.id == product.id) if (productExist && displayModal){ //update quantity productExist.quantity = parseInt(quantity) + parseInt(productExist.quantity) this.updateCart(); this.productInfo.title = "Mise à jour du produit" this.productInfo.message = "La quantité du produit sur le panier a été mise à jour"; $('.cart-toggle').trigger('click'); return true } //ADD TO CART OBJ this.addProductToCartObj(product, quantity) this.productInfo.title = "Un nouveau article a été ajouté à votre panier" this.productInfo.message = "Vous avez" + this.cart._details.length + " article(s) dans votre panier"; if (checkout){ window.location.href = "/checkout"; }else { displayModal && $('.cart-toggle').trigger('click'); } } else { let emptyOptions = []; for (let option_id in this.filterForm) { if (this.filterForm[option_id] == "") { emptyOptions.push(this.pOptions.find(x => x.id == option_id)); } } alert("Veuillez choisir :" + emptyOptions.map(x => x.name).join(', ')); return false; } }, addProductToCartObj(product, quantity=1, options = null){ let detail = {} let unit_price = this.getPriceOfProduct(product, quantity); detail['_product'] = product; detail['quantity'] = quantity; detail['product_name'] = product.name; detail['product_id'] = product.id; detail['taxe_rate'] = product.taxe_rate; detail['category_id'] = product.category; detail['product_parent_id'] = product.parent ? product.parent : product.id; detail['active_stock'] = product.active_stock; detail['product_ref'] = product.reference; detail['price_ttc_after_discount'] = unit_price; detail['product_attrs'] = product._attributs ? product._attributs.map(x => x.name).join(' ') : ''; detail['product_thumb'] = product.photo_thumb; detail['is_custom'] = product.is_custom; detail['price_ttc'] = product.price; detail['final_price'] = unit_price * quantity; detail['discount'] = product.price - unit_price; detail['options'] = options this.cart._details.push(detail) this.updateCart(); }, removeFromCart(index, e){ e.preventDefault() this.cart._details.splice(index,1) this.updateCart(); }, updateCart(){ if(this.cart._details.length == 0){ this.clearCart(); return true; } let subtotal = 0; let discount = 0; for (let prod of this.cart._details) { //GET PRODUCTS WITH SAME PARENT let parentProducts = this.cart._details.filter(product => (product._product.parent === prod._product.parent && prod._product.parent) || product._product.id == prod._product.id); //CALCULATE TOTAL QUANTITY OF THE SAME PRODUCT --> APPLY FORMULA ON ALL QUANTITY let totalQuantity = parentProducts.reduce((sum, product) => sum + parseInt(product.quantity), 0); let price_after_discount = 0; if (parentProducts.length > 1) price_after_discount = this.getPriceOfProduct(prod._product, totalQuantity); else price_after_discount = this.getPriceOfProduct(prod._product, prod.quantity); prod.final_price = parseFloat((prod.quantity * price_after_discount).toFixed(this.comma_currency)); prod.price_ttc_after_discount = parseFloat(price_after_discount.toFixed(this.comma_currency)); prod.discount = parseFloat((prod.price_ttc - price_after_discount).toFixed(this.comma_currency)); subtotal += prod.final_price; } this.setPromoCodeValue() this.cart.discount = discount this.cart.subtotal = this.cart.total_amount = subtotal if(this.getDeliveryPrice() == null) this.cart.total = this.cart.total_amount + this.cart.transport_price else this.cart.total = this.cart.total_amount + this.getDeliveryPrice() localStorage.setItem('cart', JSON.stringify(this.cart)) this.updateCartTransporter(this.cart.transport) }, updateCartTransporter(transporter){ if ( transporter && this.getDeliveryPrice() !== null){ this.cart.transport_id = transporter.id this.cart.transport = transporter this.cart.transport_price = this.getDeliveryPrice() this.cart.total = this.cart.subtotal this.cart.total += this.getDeliveryPrice() this.cart.transport.price = this.getDeliveryPrice() localStorage.setItem('cart', JSON.stringify(this.cart)) } if(transporter && this.getDeliveryPrice() == null ){ this.cart.transport_id = transporter.id this.cart.transport = transporter this.cart.transport_price = transporter.price this.cart.total = this.cart.subtotal this.cart.total += transporter.price localStorage.setItem('cart', JSON.stringify(this.cart)) } }, clearCart(){ this.cart._details = [] this.cart.transport = null this.cart.transport_price = 0 //this.cart.promoCode = "" this.cart.promoCodeDiscount = 0 this.cart.discount = 0 this.cart.subtotal = 0 this.cart.total = 0 this.cart.total_amount = 0 this.setCart(); }, setCart(event = ""){ if(this.company.works_with_transport && $('input[name="shipping"]').length){ let defaultTransporter = $('input[name="shipping"]:checked').value; if(defaultTransporter){ defaultTransporter = JSON.parse(defaultTransporter) } } event && event.preventDefault() if(this.cart.promoCode && this.cart.promoCode != ""){ this.setPromoCodeValue() }else { localStorage.setItem('cart', JSON.stringify(this.cart)) } }, //GET AUTO DISCOUNT setPromoCodeValue(){ axios .request({ url: this.api+'website/get-auto-discount', method: "POST", data: { details: this.cart._details, code: this.cart.promoCode, slug: this.company.slug, delivery_price:this.cart.transport_price } }) .then(response => { //GET AUTO DISCOUNT this.code = "autopromo" this.cart.promoCodeDiscount = response.data.toFixed(2); this.cart.discount = response.data.toFixed(2); setTimeout(()=>{ localStorage.setItem('cart', JSON.stringify(this.cart)) },100); }) .catch(error => { this.cart.promoCodeDiscount = 0 }) }, /**************************** END CART ****************************/ /**************************** SECTIONS ****************************/ getProductsForOffers(offers){ try { return offers.response.children.map(x=>x.products_widget.products_ids).flat(); } catch (error) { console.error(error); } }, getProductFrequentlyboughtTogether() { let sections = ""; let index = 0; for(let section of sections){ if (section.active && section.slug.indexOf("frequently-bought-together") != -1 ){ this.getSectionProducts({products_ids:section.products}, index); } else if (section.active && section.slug.indexOf("offers") != -1 ){ //select default section and get products this.has_offer_choice = true; this.getSectionProducts({products_ids:this.getProductsForOffers(section)}, 'offers'); let _default_index = section.response.children.findIndex(x=>x.default == true); if(_default_index != -1){ $('.offre-group .offer-item').eq(_default_index).addClass('active') }else { $('.offre-group .offer-item').eq(0).addClass('active') } setTimeout(()=>{ try { this.tempCartChoice(section.response.children[_default_index].products_widget.products_ids) } catch (error) { console.error(error); } },2000) } index++ } }, setSectionData(sections){ for(let section of sections){ if (section.slug.indexOf("products-list") != -1 ){ let desktop_display = 4.2 if (section.values.desktop_display != "0" && section.values.desktop_display){ desktop_display = section.values.desktop_display } let options = { mobile_display:section.values.mobile_display || 1.3, desktop_display:desktop_display } this.getSectionProducts(section.values.products_list, this.sectionIndex, [],options) } if(section.slug.indexOf('products-collection') != -1){ const product_list = []; for (const key in section.values) { if (key.startsWith('product_')) { product_list.push(section.values[key]); } } this.getSectionProducts({products_ids:product_list}, this.sectionIndex, []) } if(section.slug =='premium-products-carousel-with-tabs/index'){ this.sectionData[this.sectionIndex] = [] for (let index = 0; index < section.values.children.length; index++) { this.sectionData[this.sectionIndex][index]=[] this.getSectionProducts(section.values.children[index].products_list, this.sectionIndex, [], null,index) } } if(section.slug =='premium-product-list-with-tabs/index'){ this.sectionData[this.sectionIndex] = [] for (let index = 0; index < section.values.children.length; index++) { this.sectionData[this.sectionIndex][index]=[] this.getSectionProducts(section.values.children[index].products_list, this.sectionIndex, [], null,index) } } if(section.slug =='premium-product-list-1-with-tabs/index'){ this.sectionData[this.sectionIndex] = [] for (let index = 0; index < section.values.children.length; index++) { this.sectionData[this.sectionIndex][index]=[] this.getSectionProducts(section.values.children[index].products_list, this.sectionIndex, [], null,index) } } if(section.slug =='premium-product-with-deals/index'){ const product_1 = section.values.product_1 this.getSectionProducts({products_ids:[product_1]}, this.sectionIndex, []) } if(section.slug =='premium-product-with-deals-2/index'){ const {product_1,product_2} = section.values this.getSectionProducts({products_ids:[product_1,product_2]}, this.sectionIndex, []) } if(section.slug == 'premium-products-carrousel/index'){ let options = { mobile_display:1.6, desktop_display:6 } this.getSectionProducts(section.values.products_widget, this.sectionIndex, [], options) } if(section.slug =='premium-collection/index'){ this.getSectionProducts({products_ids:section.values.products_list.products_ids}, this.sectionIndex, []) } if(section.slug =='deals-outlet'){ const {product_id,product_1,product_2} = section.values this.getSectionProducts({products_ids:[product_id,product_1,product_2]}, this.sectionIndex, []) } if(section.slug == 'premium-product-group/index'){ this.sectionData[this.sectionIndex] = {} this.getSectionProducts(section.values.products_widget1, this.sectionIndex, [], null ,'products_widget1') this.getSectionProducts(section.values.products_widget2, this.sectionIndex, [], null ,'products_widget2') this.getSectionProducts(section.values.products_widget3, this.sectionIndex, [], null,'products_widget3') } if(section.slug =='deals-outlet-2'){ const product_list = section.values.children.map(x=>x.product_id); this.getSectionProducts({products_ids:product_list}, this.sectionIndex, []) } if(section.slug == "products-list-cart-builder"){ if( this.temp_cart[section.id] == undefined){ this.temp_cart[section.id] = [] } } if(section.slug == "product-featured"){ if (section.values.clear_cart){ this.cart._details = []; } let ids = section.values.children.map(child => child.one_product) let added_to_cart = section.values.children.filter(x=>x.product_added_to_cart).map(child => child.one_product) this.getSectionProducts({products_ids:ids}, this.sectionIndex, added_to_cart); for (let i = 0; i < ids.length; i++) { let id = ids[i]; this.temp_quantity[id] = 1; } } if(section.slug == "one-product"){ this.getSectionProducts({products_ids:[section.values.products_list]}, this.sectionIndex) } if(section.slug.indexOf('menu') != -1){ this.getMenuItemsById(section.values.menus_widget.menu_id, this.sectionIndex) } if (section.slug == "message"){ let msg = { "position" : section.values.position, "color" : section.values.background, "message" : section.values.text } if (section.values.text){ this.topSectionMessages.push(msg) } } this.sectionIndex++; } }, getSectionProducts(sectionValues, key, added_to_cart=[],options=null, subkey=null){ let params = "?show-children=false&company=" + this.company.id; if(sectionValues.dynamic){ let ordering = sectionValues.sort_by; let have_discount = sectionValues.have_discount; const discount__gte= { "discount_on": "1", "discount_off": "0", "both": "0", } let categories_in = sectionValues.categories_in; let size = sectionValues.length; params += "&active=true&no_parent=true&size=" + size + "&ordering=" + ordering + "&discount__gte=" + discount__gte[have_discount] + "&has_category=" + categories_in }else{ let products_ids = sectionValues.products_ids; let size = !products_ids.length ? sectionValues.length : 30 ; params += "&active=true&no_parent=true&size="+size+"&ids_in=" + products_ids.join(',') } axios. get(this.api+'products-read/'+params). then(response => { if(subkey !== null){ this.sectionData[key][subkey] = response.data.results; }else { this.sectionData[key] = sortArrayByOrder(response.data.results, sectionValues.products_ids) } setTimeout(()=>{quantityInputs()},100); let functionName = "initProductsCallback"+key; // Chaîne de texte contenant le nom de la fonction if (typeof window[functionName] === 'function') { setTimeout(()=>{window[functionName]()},50); // Appelle la fonction si elle existe } for(let id of added_to_cart){ let _product_to_add = response.data.results.find(x=>x.id == id); if(!this.cart._details.find(x=>x.product_id == id)){ this.addProductToCartObj(_product_to_add, 1); } } if($('#section-'+key+' .owl-vue-ajax').length){ let owlparams = $('#section-'+key+' .owl-vue-ajax').data('owl-options'); let defaultParams = { loop:false, margin:10, nav:true, autoplay:false, autoplayTimeout:2000, responsive:{ 0:{ items:options.mobile_display || 1.6 }, 600:{ items:3.5 }, 1000:{ items:options.desktop_display || 4.5 } } } owlparams = Object.assign({}, defaultParams, owlparams) $('#section-' + key + ' .owl-vue-ajax').addClass('owl-carousel owl-simple carousel-equal-height'); setTimeout(() => { $('#section-' + key + ' .owl-carousel.owl-vue-ajax').owlCarousel({...owlparams}); }, 100); } if($(`#section-${key} .swiper-vue-ajax`).length){ const swiperParams={ pagination: { el: `#section-${key} .swiper-pagination_product_list`, clickable: true, }, autoHeight: true, spaceBetween: 20, breakpoints: { 320: { slidesPerView: options.mobile_display || 1.6, slidesPerGroup: 1, spaceBetween: 10, }, 450: { slidesPerView: 3.5, slidesPerGroup: 2.1, spaceBetween: 15 }, 600: { slidesPerView: 3.5, slidesPerGroup: 3, spaceBetween: 15 }, 1055: { slidesPerView: options.desktop_display || 4.5, slidesPerGroup: 4, spaceBetween: 20 } } } setTimeout(() => { new Swiper(`#section-${key} .swiper-vue-ajax`, swiperParams); $(`#section-${key} .swiper-vue-ajax`).removeClass('d-none') setTimeout(() => { $(`#section-${key} .swiper-vue-ajax .swiper-wrapper`).addClass('align-items-stretch') },50) }, 1); } }) }, /**************************** END SECTIONS ****************************/ /**************************** PRODUCT ****************************/ getProducts(page){ axios. get(this.api+'products-read/?no_parent=true&active=true&show-children=false&page='+ this.productCurrentPage +'&has_category=' + this.category.id + '&company='+ this.company.id +'&size=' + this.productsSize + "&ordering=" + this.productsSort). then(response => { this.products = response.data; }) }, getFilterParams(){ axios.get(this.api+'category-filters//'+this.company.id).then(response => { this.filters = response.data; }) }, getRelatedProducts(category_id,product_id){ category_id && axios. get(this.api+'products-read/?active=true&no_parent=true&show-children=false&has_category=' + category_id + '&company='+ this.company.id +'&size=6&ids_not_in='+product_id). then(response => { this.relatedProducts = response.data['results']; }) }, changeSelectedImage(image, event){ event.preventDefault(); $("#product-zoom").attr('src', image.image) }, changeSelectedImageCarousel(event, index, id, video=false){ event.preventDefault(); $('#'+id).trigger('to.owl.carousel', index-1); $('.activeimg').removeClass('activeimg'); $(this).addClass('activeimg'); if($('video').length){ const videos = document.getElementsByTagName("video"); // Itération sur chaque vidéo et arrêt for (let i = 0; i < videos.length; i++) { videos[i].pause(); } } if (video) { $('#video-gallery-'+index).get(0).play() } }, getAttrs(product){ let attrs = '' for(let index in product._attributs){ attrs += product._attributs[index].name + " " } return attrs }, checkIfProductSelected() { let values = Object.values(this.filterForm).filter(x => x != "").length; let options = Object.keys(this.filterForm).length; return options == values }, makeNextToDefault(index){ let id = this.pOptions[index].id; this.filterForm[id] = "" }, isEnabled(option_id){ return this.attributSteps.find(x=>x.id == option_id).active }, getYoutubeEmbedUrl(url) { if(url){ let video_id = url.split('v=')[1]; let ampersandPosition = video_id.indexOf('&'); if (ampersandPosition !== -1) { video_id = video_id.substring(0, ampersandPosition); return 'https://www.youtube.com/embed/' + video_id; } } }, getMenuItemsById(id, index){ axios.get(this.api+'website/menus-read/'+id+'?company='+this.company.id). then(response => { try { this.menuItems[index-1] = response.data['menus']; } catch (exception) { console.error(exception) } }) }, enableNext(index){ //ONLY IF NOT LAST if(index+1 < this.attributSteps.length){ let current = this.attributSteps[index]; let next = this.storedAttributSteps[index+1]; this.makeNextToDefault(index+1) this.attributSteps[index+1].active = true; this.attributSteps[index+1].options = this.getNextAttributs(next.id, this.filterForm[current.id], index); } setTimeout(()=>{ let values = Object.values(this.filterForm).filter(x => x != ""); this.products_filtered = this.product.declinaisons.filter(x => { return values.every((val) => x.attributs.includes(parseInt(val))) }); },100) }, selectColor(option, color, id, $event){ $event.preventDefault(); this.filterForm[option.id] = color.id; this.colorSelected = color.id; let img = color.image; let index = 0; this.filterSubProduct(option.id, color.id) for(_img of this.product_images_list){ if(_img.image == img){ $('#'+id).trigger('to.owl.carousel', [index,0]); $('#'+id+"-snippet").trigger('to.owl.carousel', [index,0]); $('#'+id+"-snippet .owl-item").eq(index).find('.product-gallery-item').addClass('activeimg') } index++; } }, getNextAttributs(next_option_id) { let optionValues = []; let filtred = this.product.declinaisons; let choices = Object.values(this.filterForm).filter(x=>x != '').map((x)=>parseInt(x)) //FILTER PRODUCTS BY FILTER FORM filtred = this.product.declinaisons.filter(declinaison =>{ return choices.every(element => declinaison.attributs.indexOf(element) > -1) && (declinaison.active_stock && declinaison.stock >= 1 || !declinaison.active_stock); }); let allAttributes = filtred.map(x=>x.attributs).flat() let possibleValues = this.pOptions.map(x=>x.values.map(y=>y.id)).reduce((acc, val) => acc.concat(val), []); optionValues = allAttributes.filter(value => possibleValues.includes(value)); let option = this.pOptions.find(x=>x.id == next_option_id); return option.values.filter(y=>optionValues.includes(y.id)); }, getOption(option){ try { return option.values.find(x=>x.id == this.filterForm[option.id]).name } catch (error) { return "" } }, regroupDeclinaisonsPerColor(product) { const regroupement = {}; product.declinaisons.forEach(declinaison => { const couleurAttribut = declinaison._attributs.find(attr => attr.is_color); if (couleurAttribut) { const couleur = couleurAttribut.value; if (!regroupement[couleur]) { regroupement[couleur] = []; } regroupement[couleur].push(declinaison); } }); return regroupement; }, buildAttributs() { if(this.product.declinaisons.length) { for (let declinaison of this.product.declinaisons) { if (this.product.active_stock && declinaison.stock >= 1 || !this.product.active_stock) { for (let attr of declinaison._attributs) { //BUILD ATTRS (this.product_options.indexOf(attr.productoption) == -1) && this.product_options.push(attr.productoption); (this.product_attributs.indexOf(attr.id) == -1) && this.product_attributs.push(attr.id); } } } for (let option of this.product_options) { this.filterForm[option] = "" } } this.product_options.length && axios. get(this.api+'product-options-read/?ids_in='+this.product_options.join(',')+'&company='+this.company.id). then(response => { this.pOptions = response.data; this.pOptions.sort((a,b)=> { return b.is_color_group - a.is_color_group; }); //DEFINE STEPS let i = 0; for(let option of this.pOptions){ let _options = this.product_attributs.filter(value => option.values.map(x=>x.id).includes(value)); let _obj = {id:option.id, active : i === 0? true : false, options:option.values.filter(x=>_options.includes(x.id))}; this.attributSteps.push(_obj); this.storedAttributSteps.push(JSON.parse(JSON.stringify(_obj))) i++; } setTimeout(()=>{ if($('.color-pick:not(.association)').length == 1){ $('.color-pick')[0].click(); } },200) }) }, /**************************** END PRODUCT ****************************/ /**************************** WISHLIST ****************************/ addToWishlist(productId, event){ event.preventDefault() if(!this.user.customer.favourite.includes(productId)){ this.user.customer.favourite.push(productId) this.updateUser() } }, is_new_prorduct(product){ product = product ? product : this.product; let now = new Date(); let date_limit = this.product_settings.product_is_new ? this.product_settings.product_is_new : 15 let product_date = new Date(product.created_at) let diff = new Date(now - product_date); if (diff/86400000 <= date_limit){ return 'true'; } }, RemoveFromWishlist(index){ this.user.customer.favourite.splice(index,1) this.whishlistProducts.splice(index,1) this.updateUser() }, getWishlistProducts(){ let ids = this.user.customer.favourite.map(id => id).join(',') axios. get(this.api+'products-read/?ids_in='+ ids +'&company='+ this.company.id +'&size=50'). then(response => { this.whishlistProducts = response.data.results; }) }, /**************************** END WISHLIST ****************************/ /**************************** USER ****************************/ login(redirect = false) { this.loginForm.username= this.loginForm.email+"_"+this.company.id; this.loginFormError = false this.ErrorMessage = "" let prefix = '';//'/'+this.currentLanguage; axios. post(this.api+'auth/login/', this.loginForm). then(response => { this.user = response.data.user; this.logged = true this.token = response.data.key localStorage.setItem('user', JSON.stringify(this.user)); localStorage.setItem('user_id', this.user.id); localStorage.setItem('_token', response.data.key); document.cookie = "token="+this.token; redirect && window.location.replace(prefix+'/account') $('#signin-modal').modal('hide'); }) .catch(error => { this.loginFormError = true if(error.response.status == 400){ for(let err in error.response.data){ this.ErrorMessage += error.response.data[err] + " " } }else { this.ErrorMessage = "Une erreur est survenue, merci de contacter l'admin" } }); }, register(){ this.signUpFormError = false this.ErrorMessage = "" this.signUpForm.username = this.signUpForm.email+"_"+this.company.id; this.signUpForm.code_tva = 0 this.signUpForm.company = this.company.id; axios. post(this.api+'register-user', this.signUpForm). then(response => { if (response){ this.user = response.data; this.logged = true this.token = this.user.token localStorage.setItem('user', JSON.stringify(this.user)); localStorage.setItem('user_id', this.user.id); localStorage.setItem('_token', this.user.token); window.location.href = '/account' $('#signin-modal').modal('hide'); } }) .catch(error => { this.signUpFormError = true for(let err in error.response.data){ this.ErrorMessage += error.response.data[err] + " " } }); }, logout(){ localStorage.removeItem('user'); localStorage.removeItem('_token'); localStorage.removeItem('user_id'); document.cookie ='token=; Max-Age=0' window.location.href = '/' }, updateUser(){ this.UserSubmitMessage = "" axios .request({ url: this.api+'website/customer-update/', method: "POST", headers: { Authorization: "Token " + this.token, }, data: this.user.customer }) .then(response => { this.UserSubmitError = false this.UserSubmitMessage = "Vos informations ont été enregistrées avec succès" localStorage.setItem('user', JSON.stringify(this.user)) }) .catch(error => { this.UserSubmitError = true this.UserSubmitMessage = "Un erreur est survenue, veuillez réessayer plus tard" }) }, resetPasswordRequest(){ this.loginFormError = true this.ErrorMessage = "" let user = { email: this.resetPasswordEmail.toLowerCase() , company_id: this.company.id, website: window.location.origin.split('/')[2] } axios. post(this.api+'website/reset-password', user). then(response => { this.loginFormError = false }) .catch(error => { this.loginFormError = true // for(let err in error.response.data){ // this.ErrorMessage += error.response.data[err] + " " // } this.ErrorMessage = "Une erreur est survenue, veuillez vérifier votre email ou bien de contacter l'admin" }); }, resetPasswordConfirm(){ let queryString = window.location.search; let urlParams = new URLSearchParams(queryString); let username = urlParams.get('username') let token = urlParams.get('token') let user = { username: username, password: this.resetPass1, confirm_password: this.resetPass2, token: token } this.resetPasswordError = false this.ErrorMessage = "" axios. post(this.api+'website/reset-password-confirm', user). then(response => { this.resetPassword = false this.logged = true this.user = response.data.user this.token = response.data.token localStorage.setItem('user', JSON.stringify(this.user)); localStorage.setItem('user_id', this.user.id); localStorage.setItem('_token', this.token); //window.location.href = "/" }) .catch(error => { this.resetPasswordError = true for(let err in error.response.data){ this.ErrorMessage += error.response.data[err] + " " } }); }, openAddressModal(address, index){ this.addressToEdit = address this.selectedAddressIndex = index $('#address-modal').modal('show'); }, updateCustomerAddress(){ this.user.customer.addresses[this.selectedAddressIndex] = this.addressToEdit axios .request({ url: this.api+"website/addresses/"+this.addressToEdit.id+"/", method: "PATCH", headers: { Authorization: "Token " + this.token }, data: this.addressToEdit }) .then(response => { setTimeout(()=>{ localStorage.setItem('user', JSON.stringify(this.user)) },100) }) $('#address-modal').modal('hide'); }, addAdress(){ let address = { "id": null, "title": "Nouvelle addresse", "address": "addresse", "default": false, "code_tva": "", "gouvernorat": "Ariana", "delegation": "Ariana", "contact": "", "code_postal": "", "phone": "", "phone_extra": "", "customer": this.user.customer.id } axios .request({ url: this.api+"website/addresses/", method: "POST", headers: { Authorization: "Token " + this.token }, data: address }) .then(response => { setTimeout(()=>{ localStorage.setItem('user', JSON.stringify(this.user)) },100) this.user.customer.addresses.push(response.data) this.openAddressModal(response.data, this.user.customer.addresses.length-1) }) }, deleteAdress(index, event){ event.preventDefault() let address = this.user.customer.addresses[index] axios .request({ url: this.api+"website/addresses/"+address.id+"/", method: "DELETE", headers: { Authorization: "Token " + this.token }, data: address }) .then(response => { this.user.customer.addresses.splice(index,1) setTimeout(()=>{ localStorage.setItem('user', JSON.stringify(this.user)) },100) }) }, /**************************** END USER ****************************/ sendContactForm($event){ this.loading = true; axios .request({ url: this.api + "applications/form-contact", method: "POST", data:{ form: this.contact, company: this.company.id } }) .then((response) => { if(response.status == 200){ this.loading = false; alert('Message sent successfully') } else { this.loading = false; alert("Il y a une erreur") } }); }, getBasicPackProducts(page){ let products_in_pack = axios.get(this.api+'products-read/?no_parent=true&page='+ page +'&active=true&ids_in='+ products_in_pack.join(',') + '&company='+ this.company.id +'&size=10' ). then(response => { this.products = response.data; }) }, getPackProducts(page){ let products_in_pack = axios.get(this.api+'products-read/?page='+ page +'&active=true&ids_in='+ products_in_pack.join(',') + '&company='+ this.company.id +'&size=10'). then(response => { this.packProducts = duplicateProductsByIds(response.data.results, products_in_pack); //fill no declinaison products in pack setTimeout(()=>{ let index = 0; this.packProductCart[this.product.id] = [] for (subproduct of this.packProducts){ if(!subproduct.declinaisons.length){ this.packProductCart[this.product.id][index] = { product : subproduct, quantity:1, id:subproduct.id, attrs:'', photo_thumb:subproduct.photo_thumb }; }else { this.packProductCart[this.product.id] = [] for(item in this.product.features){ this.packProductCart[this.product.id][item] = ""; } } index++ } localStorage.setItem('pack_product_cart', JSON.stringify(this.packProductCart)) },100) }) }, /**************************** ORDER ****************************/ addUpsell($event, upsell, order_ref){ axios .request({ url: this.api + "update-order-upsell", method: "POST", data:{ upsell: upsell, order: order_ref, company: "", } }).then((response) => { if(response.status == 200){ window.location.href = "/checkout-confirmation/"+order_ref } else { this.loading = false; alert("Il y a une erreur") } }); }, sendSMSConfirmationClient(event,order, company){ this.loading = true axios .request({ url: this.api + "send-sms-client-confirmation", method: "POST", data:{ order: order, company: company, } }).then((response) => { if(response.data.verifcation){ this.loading = false alert(response.data.msg) window.location.href = "/checkout-confirmation/" + order.order_code + "?sms_sent=true"; } else { this.loading = false; alert(response.data.msg) window.location.href = "/" } }); }, verifyOTP(event,order,company){ const { number1, number2, number3, number4 } = this.SMSConfirmationForm; if ( number1 == '' || number2 == '' || number3 == '' || number4 == '' ) { alert("Veuillez remplir le code") } else { this.loading = true const code_to_verify = number1.toString() + number2.toString() + number3.toString() + number4.toString(); axios .request({ url: this.api + "verify-otp", method: "POST", data:{ company: company, code:code_to_verify } }).then((response) => { if(response.data.verifcation){ this.loading = false window.location.href = "/confirm-client/" + order.order_code + "/" + this.company.id; } else { this.loading = false; alert("Veuillez vérifier le code saisie") } }); } } , createOrder($event,online_payment=true){ if( !this.cart._details.length){ alert('Panier vide'); this.hideLoading(); return false; } this.displayLoading(); //PARSE localstorage this.cart._details.forEach((detail) => { let _data = localStorage.getItem('product_upload_'+detail.product_parent_id) if (_data) { // Récupérer la valeur du localStorage et l'ajouter à l'objet detail.comment = _data; detail.options = 'uploads' localStorage.removeItem('product_upload_'+detail.product_parent_id); } }); this.loading = true; this.order.transport_id = this.cart.transport ? this.cart.transport.id : null this.order.total_amount = this.cart.total_amount this.order._details = this.cart._details.filter(x=>x.quantity>0); let headerConfig = this.logged ? {Authorization: "Token " + this.token} : null; let champs = ["email","name","contact","gouvernorat","delegation","address","code_postal","phone","phone_extra"]; for(let item of champs){ if(!this.order[item] && $('#checkout_'+item).length){ this.order[item] = $('#checkout_'+item).val(); } } setTimeout(()=>{ axios .request({ url: this.api + "create-fast-order/", method: "POST", headers: headerConfig, data:{ abandonned_cart:localStorage.getItem('abandonned_cart'), order: this.order, promo_code: this.cart ? this.cart.promoCode :"", company: this.company.id, create_account: this.createAccount } }) .then((response) => { if(response.status == 200){ //if payment online redirection only and dont delete anything if(this.order.payement_type == 'ONLINE' && response.data.payment.payUrl && online_payment){ window.location.href = response.data.payment.payUrl }else { //if order without payment, clear cart, open message, close loading this.clearCart(); if(response.data.upsell_id != "" && response.data.upsell_id){ window.location.href = "/upsell/"+response.data.upsell_id+'/'+response.data.order_ref }else { window.location.href = "/checkout-confirmation/"+response.data.order_ref } } } else { this.loading = false; alert("Il y a une erreur") } }); },50) }, createOrderAbandonned(){ this.cart._details.forEach((detail) => { let _data = localStorage.getItem('product_upload_'+detail.product_parent_id) if (_data) { // Récupérer la valeur du localStorage et l'ajouter à l'objet detail.comment = _data; detail.options = 'uploads' localStorage.removeItem('product_upload_'+detail.product_parent_id); } }); this.order.transport_id = this.cart.transport ? this.cart.transport.id : null this.order.total_amount = this.cart.total_amount this.order._details = this.cart._details.filter(x=>x.quantity>0); if(this.order._details.length == 0){ if (this.products_filtered.length ){ let _product = this.products_filtered[0]; this.order._details = [{quantity:1, product_id:_product.id}]; }else { this.order._details = this.cart._details; } } let headerConfig = this.logged ? {Authorization: "Token " + this.token} : null; let champs = ["name","contact","gouvernorat","delegation","address","code_postal","phone","phone_extra"]; for(let item of champs){ if(!this.order[item] && $('#checkout_'+item).length){ this.order[item] = $('#checkout_'+item).val(); } } setTimeout(()=>{ axios .request({ url: this.api + "create-fast-order/", method: "POST", headers: headerConfig, data:{ is_abandoned_cart:true, order: this.order, promo_code: this.cart ? this.cart.promoCode :"", company: this.company.id, create_account: this.createAccount } }) .then((response) => { if(response.status == 200){ localStorage.setItem('abandonned_cart',response.data.order_ref) } }); },50) }, setPaymentType(type){ this.order.payement_type = type }, setDefaultPaymentType(){ let has_cash = true; let has_online = false && false; let default_type = "CASH"; if (has_online && default_type == 'ONLINE'){ return 'ONLINE' } return 'CASH' }, getDeliveryPrice(){ // Check if any product has custom_delivery_price set to false ==> SHOW TRANSPORT PRICES NO MATTER WHAT const hasNonCustomDelivery = this.cart._details.some(x => !x._product.custom_delivery_price); if (hasNonCustomDelivery) return null; let custom_delivery_price = null; let custom_delivery_price_list = this.cart._details .filter(x => x._product.custom_delivery_price) .map(x => x._product.delivery_price); if (custom_delivery_price_list.length) { custom_delivery_price = custom_delivery_price_list.reduce((max, price) => { return max > price ? max : price; }, -Infinity); } return custom_delivery_price; }, getCustomerOrders(){ axios .request({ url: this.api + "website/get-customer-orders/", method: "GET", headers: { Authorization: "Token " + this.token } }) .then((response) => { this.customerOrders = response.data.slice(0, 5) }); }, openPreviewProduct(product){ this.modalProduct = product; $('body').addClass('modal-open') setTimeout(()=>{ $('.modalOverlay_p_i_3').addClass('open').children('.modal_p_i_3').addClass('flipped'); setTimeout(()=>{ initializeSwiper(); },10) },10) }, closePreviewProduct(){ $('body').removeClass('modal-open') $('.modalOverlay_p_i_3').removeClass('open').children('.modal_p_i_3').removeClass('flipped') setTimeout(()=>{ this.modalProduct = null; },500) }, /**************************** END ORDER ****************************/ /**************************** SEARCH ****************************/ searchCall(){ window.location.href = '/search?products='+this.search }, searchCall_h_9(){ window.location.href = '/search?products='+this.searchMenu }, calculateStock(product) { try { if (product && product['declinaisons'].length > 0) { let total_stock = 0; for (const dec of product['declinaisons']) { total_stock += dec['stock']; } return total_stock; } else { return product['stock']; } } catch (error) { console.error(error); } }, searchProducts(string = ""){ this.ProductsSearch = {results:[]}; let queryString = window.location.search; let urlParams = new URLSearchParams(queryString); let searchParam = string || urlParams.get('products') if(searchParam && searchParam != ""){ axios. get(this.api+'products-read/?company='+ this.company.id +'&no_parent=true&active=true&show-children=false&search=' + searchParam). then(response => { this.ProductsSearch = response.data; }) } }, quitsearch(){ this.ProductsSearch = {results:[]}; this.searchMenu = ""; }, searchCollection(searchParam){ this.collectionSearch = null; if(searchParam){ axios. get(this.api+'categories-read?company='+ this.company.id +'&active=true&search=' + searchParam). then(response => { this.collectionSearch = response.data; }) } }, get_prod_attrs(prod){ let attrs = []; let attrs_str = ''; try { for ( let attr of prod._attributs) { attrs.push(attr.name); } attrs_str = attrs.join(' ') return attrs_str }catch (error) { return '' } }, checkMaxStock(product){ try { if(product.quantity > product._product.stock) { product.quantity = product._product.stock } return product._product.stock } catch (error) { console.log(error) } }, decrement(product_temp_id){ if(this.temp_quantity[product_temp_id] > 1){ this.temp_quantity[product_temp_id] -=1; } }, increment(product_temp_id){ this.temp_quantity[product_temp_id] +=1; }, CheckandUpdateStockbeforeCheckout(){ let verif = false try { this.cart._details.forEach((detail) => { if(detail.quantity > detail._product.stock){ verif = true; detail.quantity = detail._product.stock this.updateCart(); } }); window.location.href = "/checkout"; /*if (verif) { this.productInfo.title = "Stock épuisé"; this.productInfo.message = "Produit en rupture de stock"; $('#check-max-stock-modal').modal(); } else { window.location.href = "/checkout"; }*/ } catch (error) { console.log(error) window.location.href = "/checkout"; } }, searchProductsPagination(apiUrl){ axios. get(apiUrl.replace('http:','https:')). then(response => { this.ProductsSearch = response.data; }) }, initializeFiltersFromURL() { // Extract parameters from URL const urlParams = new URLSearchParams(window.location.search); const hasAttributs = urlParams.get('has_attributs'); const hasCategory = urlParams.get('has_category'); const min_price = urlParams.get('price_gte'); const max_price = urlParams.get('price_lte'); const page = urlParams.get('page'); const ordering = urlParams.get('ordering'); // Initialize `filters_product` based on URL parameters if (hasAttributs && hasAttributs.trim() !== '') { this.filters_product.attributs = hasAttributs.split(',').map(Number); // Set attributes } else { this.filters_product.attributs = []; // Clear attributes if none provided } if (hasCategory && hasCategory.trim() !== '') { this.filters_product.sub_categories = hasCategory.split(',').map(Number); // Set categories } else { this.filters_product.sub_categories = []; // Clear sub-categories if none provided } if ((this.filters_product.min_price != null && this.filters_product.min_price !== 0) || (this.filters_product.max_price != null && this.filters_product.max_price !== 30000)) { this.filters_product.min_price = Number(min_price) this.filters_product.max_price = Number(max_price) } if(page){ this.fetchProducts(page,this.category.id,page); }else{ this.fetchProducts(1,this.category.id); } if(ordering && ordering != ''){ this.productsSort = ordering } }, toggleAttribute(id, attr, category_id) { const index = this.filters_product[attr].indexOf(id); if (index === -1) { // Add ID if it doesn't exist this.filters_product[attr].push(id); } else { // Remove ID if it exists this.filters_product[attr].splice(index, 1); } // Fetch updated products and update URL this.fetchProducts(1,category_id); }, fetchProducts(page=1, category_id = null) { let noUiSliderInitfunctionName = Object.keys(window).filter(key => key.startsWith("initNouislider") ); if (noUiSliderInitfunctionName.length) { noUiSliderInitfunctionName.forEach((funcName) => { window[funcName]() }) } // console.log(Object.keys(window)); this.products = [] const attributsString = this.filters_product.attributs.join(','); let subcategoriesString = this.filters_product.sub_categories.join(','); // If `sub_categories` is empty and `category_id` is provided, don't set `subcategoriesString` to `category_id` if (this.filters_product?.sub_categories?.length === 0 ) { subcategoriesString = String(this.category.id); } // Update the URL only if there are valid parameters to add const url = new URL(window.location); // CATEG if (attributsString) { url.searchParams.set('has_attributs', attributsString); } else { url.searchParams.delete('has_attributs'); } //ATTRS if (subcategoriesString && !subcategoriesString?.includes(this.category.id)) { url.searchParams.set('has_category', subcategoriesString); // Add `has_category` only if not empty } else { url.searchParams.delete('has_category'); // Remove `has_category` if subcategoriesString is empty } // Handle the price filters and remove them if they are the default values if (this.filters_product.min_price > 0) { url.searchParams.set('price_gte', this.filters_product.min_price); } else { url.searchParams.delete('price_gte'); // Remove price_gte if it's 0 } if (this.filters_product.max_price < 30000) { url.searchParams.set('price_lte', this.filters_product.max_price); } else { url.searchParams.delete('price_lte'); // Remove price_lte if it's 120000 } //PAGE if (page > 1) { url.searchParams.set('page', page); } else { url.searchParams.delete('page'); // Remove price_lte if it's 120000 } // SORT BY let ordering = ''; if (this.category.sort != '' && this.productsSort == ''){ if (this.category.sort != 'manually') { ordering = this.category.sort url.searchParams.delete('ordering') } else { ordering = 'order' url.searchParams.delete('ordering') } } if (this.productsSort != ''){ ordering = this.productsSort url.searchParams.set('ordering', this.productsSort) } if (this.category.sort == '' && this.productsSort == ''){ ordering='' url.searchParams.delete('ordering') } window.history.replaceState(null, '', url.toString()); // Make the API call with the modified parameters axios .get( `${this.api}products-read/?company=${this.company.id}&page=${page}&ordering=${ordering}&size=${this.productsSize}&no_parent=true&active=true&show-children=false&has_attributs=${attributsString}&has_category=${subcategoriesString}&price_gte=${this.filters_product.min_price}&price_lte=${this.filters_product.max_price}` ) .then((response) => { this.products = response.data; }); }, resetFilterProducts(category_id){ this.filters_product.attributs = [] this.filters_product.sub_categories = [] this.filters_product.min_price = 0; this.filters_product.max_price = 30000; this.fetchProducts(1,category_id) }, sendEventFacebookConversion(event_type, data = {}) { let facebook_token = '465657706620624'; let details = this.cart._details.filter(x => x.quantity > 0).map(x => ({ id: x.product_parent_id, quantity: x.quantity })); facebook_token && axios.post('/send-event', { access_token: '465657706620624', event_id: this.event_id, pixel: '465657706620624', event_type: event_type, url: window.location.href, client_user_agent:navigator.userAgent, currency:'TND', cart:details, pixels : other_pixels, ...data }, { headers: { 'X-CSRFToken': "8XBgBS5vOjOA5KRRD9Cx26li7heQyA3FIYtAtxEO7LAe9znQGfEcMfBZtnMo78hb", 'Content-Type': 'application/json' } }) }, sendCheckoutFacebookConversion(){ /* let details = this.cart._details.map(x=>{id:x.product_parent_id, quantity:x.quantity}) let products = this.cart._details.map(x=>x.product_parent_id) //FACEBOOK PIXEL fbq('track', 'Purchase',{ currency: "TND", value: this.cart.total, contents:details }, { eventID : "dj1WrkG1743726309890.3726" } ); fetch('/send-event', { method: 'POST', body: JSON.stringify({ access_token: '465657706620624', pixel: '465657706620624', event_id: "dj1WrkG1743726309890.3726", url: window.location.href, currency:'TND', event_type :'Purchase', cart:details, data:{phone:this.order.phone, email:this.order.email}, price:this.cart.total }), headers: { 'X-CSRFToken': "8XBgBS5vOjOA5KRRD9Cx26li7heQyA3FIYtAtxEO7LAe9znQGfEcMfBZtnMo78hb", 'Content-Type': 'application/json' } }) .then(response => { // Gérer la réponse ici console.log('Page view sent'); })*/ } /**************************** END SEARCH ****************************/ }, data() { return { api: "https://api.tiktak.space/api/v1/", event_id:"dj1WrkGdj1WrkG1743726309890.3726", loading : false, order_message:'', colorSelected : '', availableColors :[], //LOGIN & SIGN UP logged: false, loginForm: { "username": "", "email": "", "password": "", }, loginFormError: false, signUpForm: { "first_name": "", "last_name": "", "email": "", "phone": "", "phone_extra": "", "password": "", "password2": "", "profile": false, "username": "", "company": "", "code_tva": null }, signUpFormError: false, resetPassword: false, resetPasswordError: false, resetPasswordEmail: "", resetPasswordErrorMessage: "", resetPass1: "", resetPass2: "", packProductCart:{}, ErrorMessage: "", search: "", searchMenu:"", company : null, token : null, addressToEdit: {}, selectedAddressIndex: null, modalProduct:null, filters :null, user: { "customer": { "favourite": [], "addresses": [ {} ] }, "name": "", "email": "", "phone": "", "phone_extra": "", "code_tva": "", }, UserSubmitError: false, UserSubmitMessage: "", message_test:"", currentLanguage : "fr", temp_quantity:{}, temp_cart: localStorage.getItem('temp_cart') ? JSON.parse(localStorage.getItem('temp_cart')) : {}, cart: { "_details":[], "transport": null, "transport_price": 0, "promoCode": "", "promoCodeDiscount": 0, "discount": 0, "subtotal": 0, "total": 0, "total_amount": 0, }, productQte: 1, menuItems:{}, order: { "email": "", "name": "", "contact": "", "gouvernorat": "", "delegation": "", "address": "", "code_postal": "", "phone": "", "phone_extra": "", "country": "TN", "comment": "", "payement_type": this.setDefaultPaymentType(), "transport_id": null, "total_amount": 0, "_details": null }, createAccount: false, whishlistProducts: [], ProductsSearch: { "count": 0, "current_page": 1, "next": null, "previous": null, "results": [], "total_pages": 1 }, collectionSearch:{ "count": 0, "current_page": 1, "next": null, "previous": null, "results": [], "total_pages": 1 }, has_pixel: false, comma_currency:"1.3-3".charAt("1.3-3".length - 1), customerOrders: [], instagramfeed:[], //sections sectionData: {}, sectionIndex: 1, extraData:{}, //section messages topSectionMessages : [{ "position": "before-header", "color": null, "message": "" }], bottomSectionMessages : [{ "position": "after-footer", "color": null, "message": "" }], sectionMessages : [{ "position": 'null', "color": null, "message": "" }], associated_products:[], relatedProducts:[], stock_settings:{"default_product_stock": false, "display_stock_onwebsite": false}, contact:{email:"", name:"", message:""}, product_settings : {"style": {"price_size": 12, "title_size": 25, "price_color": "#000000", "title_color": "#000000", "shadow_value": 0, "border_radius": 0}, "product_is_new": 15, "product_label_discount": "En promo", "product_out_of_stock_redirection": "showProductPage"}, category_settings : {}, //product product: null, product_images_list: {} , product_options: [], product_attributs: [], pack_products_corss_sell : null, products_corss_sell : {}, filterForm: {}, attributSteps: [], products_filtered: [], pOptions: null, storedAttributSteps: [], transporters:[], //product list productsSize: 20, productCurrentPage:1, productsSort: "", productInfo: { "title": "", "message":"" }, visitors:Math.floor(Math.random() * 26) + 5, category: null, products: { "count": 0, "current_page": 1, "next": null, "previous": null, "results": [], "total_pages": 1 }, packProducts:[], options: [], gouvernorats : GOUVERNORATS, countries : COUNTRIES, has_offer_choice:false, SMSConfirmationForm: { "number1": "", "number2": "", "number3": "", "number4": "" }, filters_product: { sub_categories: [], attributs: [], min_price : 0 , max_price : 30000 }, } }, beforeMount() { //this.init() }, mounted() { this.init(); const urlParams = new URLSearchParams(window.location.search); const coupon = urlParams.get('coupon'); if (coupon) { this.cart.promoCode = coupon; setTimeout(()=>{ localStorage.setItem('cart', JSON.stringify(this.cart)) },1000); axios .request({ url: this.api+'website/get-discount-code', method: "POST", data: { code: this.cart.promoCode, slug: this.company.slug, } }) .then(response => { this.code = coupon if(response.data.display_settings){ const banner = `
${response.data.display_settings.text}
`; $("body").prepend(banner); } }) .catch(error => { this.cart.promoCodeDiscount = 0 }) } //panier abandonné setTimeout(()=>{ $('#checkout_phone').on('input', ()=>{ let phone = $('#checkout_phone').val(); if(phone.replace(/\s/g, "").length == parseInt($('#checkout_phone').data('max'))){ this.createOrderAbandonned(); } }); },200) } }).mount('#tiktak-store-app');