/* eslint-disable no-alert, no-console , no-debugger */ import { getDomain, getCookieByName, removeCookieByName } from "@/services/auth"; export const doFormatAddress = (address) => { let newaddress = address.streetNoOne + " " + address.city + " " + address.regionId + " " + address.countryId; return newaddress; }; export const fetchStates = (countryId, countryWiseStates) => { let oneCountry = countryWiseStates.filter( states => { return states.id == countryId; } ); if (oneCountry.length > 0 && oneCountry[0].availableRegions) { let allStates = oneCountry[0].availableRegions.map(val => { return { value: val.id, label: val.name }; }); return allStates; } else { return [{ "value": "", "label": "No States Found" }]; } } export const attribute = (customAttributes, attributeCode, productAttributes) => { if (productAttributes.items && customAttributes) { let result = customAttributes.filter(element => { return element.attributeCode === attributeCode; }); if (result.length > 0) { let val = result[0].value; //254 //uom let newValue = productAttributes.items.filter(elements => { return elements.attributeCode === attributeCode }); let filter = newValue[0].options.filter(elementNew => { return elementNew.value === val }); if (filter.length > 0) { return filter[0].label; } } } } export const customAttributeValueNew = (customAttributes, attributeCode) => { let result = customAttributes.filter(element => { return element.ac === attributeCode; }); if (result[0]) return result[0].v; else return ''; } export const customAttributeValue = (customAttributes, attributeCode) => { let result = customAttributes.filter(element => { return element.attributeCode === attributeCode; }); if (result[0]) return result[0].value; else return ''; } export const getLable = (customAttributes, attributeCode) => { let result = customAttributes.filter(element => { return element.attributeCode === attributeCode; }); if (result[0]) return result[0].label; else return ''; } export const getMeta = (data) => { let metaObj = {}; if (data) { data.filter(element => { if (element.attributeCode === "meta_title") metaObj.title = element.value; if (element.attributeCode === "meta_description") metaObj.description = element.value; if (element.attributeCode === "meta_keywords") metaObj.keywords = element.value; if (element.attributeCode === "meta_keyword") metaObj.keywords = element.value; }); } return metaObj; } export const getCategoryOne = (list, categoryId) => { let result = list.filter(element => { return element.id === categoryId; }); if (result[0]) return result[0]; else return ''; } export const commonValidationRules = { noRules: [], passwordRule: [ v => !!v || "Password is required", v => /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,}$/.test(v) || "Password must contain atleast one lowercase, one uppercase, one digit and one special character" ], } export const goToCategoryPage = (vm, category, subCategory, subChlid, categoryId) => { vm.$router .push({ name: "CategoryPage", params: { category: category, subCategory: subCategory, subChlid: subChlid }, query: { "pageNumber": 1, "pageSize": "9", "sortBy": "position", //"category": categoryId, "filter": 'e30=' }, meta: { id: categoryId } }).catch(error => { error; }); } export const goToCategoryPageRouting = (vm, category) => { vm.$router .push({ name: category.n + "_" + category.id, /* query: { "pageNumber": 1, "pageSize": "9", "sortBy": "position", "filter": 'e30=' },*/ }).catch(error => { error; }); } function getlabelValue(customAttributes, attributeCode) { let result = customAttributes.filter(element => { return element.attributeCode === attributeCode; }); if (result[0]) return result[0].label; else return ''; } function getlabelValuePurchase(customAttributes) { try { let label = JSON.parse(customAttributes); if (label) return label.label; else return ''; } catch (error) { console.log("error", error); return ""; } } export const getCategoriesPurchase = (product) => { try { let categoryLink = product.extensionAttributes.categoryLinks; for (let i = 0; i < 2; i++) { let newVal = JSON.parse(categoryLink[i]); if (newVal) { return newVal.category_name; } } } catch (error) { console.log("error", error); return ""; } return ""; } export const googleAanalytics = (vm, res, productDetails, qtyNew, action, name) => { setTimeout(() => { let catName = null; if (getCookieByName(res.item_id)) { catName = getCookieByName(res.item_id) catName = catName.split(':')[0]; } else if (productDetails.extensionAttribute.catagoryLinks[0]) { catName = productDetails.extensionAttribute.catagoryLinks[0].categoryName; } let gtag = window.gtag ? window.gtag : null; if (gtag) { gtag('event', action, { "items": [{ 'id': productDetails.sku, 'name': productDetails.name, 'category': catName, 'brand': getlabelValue(productDetails.customAttribute, "brand"), 'price': res.price, 'quantity': qtyNew }] }); } console.log("google analytics called ", action, name); }, 500) } export const googleAanalyticsEventRemoveCart = (action, productDetails) => { let gtag = window.gtag ? window.gtag : null; if (gtag) { gtag('event', action, { "items": [{ 'id': productDetails.sku, 'name': productDetails.name, //'category': category, //'brand': getlabelValue(productDetails.customAttribute, "brand"), 'price': productDetails.price, 'quantity': productDetails.qty }] }); } console.log("google analytics called ", action); } export const googleAanalyticsEventSelectContent =async (action, productDetails,categoryId) => { let category = '' let listName = '' if (categoryId) { listName = "Category Results" category = await getCatPath(categoryId) } else { listName = "Search Results" category = "Search" } let gtag = window.gtag ? window.gtag : null; if (gtag) { let item = [] let productPrice = '' if (productDetails.lp) { productPrice = productDetails.lp } else { if (productDetails.sp) { productPrice = roundUp(productDetails.sp) } else if (productDetails.p != 0) { productPrice = productDetails.p } } item.push({ 'id': productDetails.sku, 'name': productDetails.n, 'list_name': listName, 'brand': productDetails.b, 'category':category, 'variant': productDetails.dc, 'price': productPrice, //'quantity': productDetails.qty }) if (item.length > 0) { gtag('event', action, { "content_type": "product", "items": item }); } } console.log("google analytics called ", action); } export const criteoForProductList = (productList) => { let productIds = []; if (productList.length) { for (let p = 0; p < productList.length; p++) { productIds.push(productList[p].id); if (p == 2) break; } window.criteo_q.push( { event: "viewList", item: productIds } ); console.log("view product list", productIds); // checkDataLayerPropDuplication("ListingPage", "ProductIDList", productIds); } }; export const criteoForCurrentProduct = (productId) => { if (productId) { window.criteo_q.push( { event: "viewItem", item: productId } ); console.log("view product", productId); // checkDataLayerPropDuplication("ProductPage", "ProductID", productId); } }; export const criteoUpdateUserEmail = (email) => { window.criteo_q.push( { event: "setEmail", email: email } ); console.log("user email", email); }; export const criteoViewBasket = (list) => { let items = []; for (let i = 0; i < list.length; i++) { let item = list[i]; items.push( { id: item.stockDetails.productId, price: item.price, quantity: item.qty } ); } if (items.length > 0) { window.criteo_q.push( { event: "viewBasket", item: items }); } console.log("view basket", items); }; export const listrakCartList = (list) => { let items = []; for (let i = 0; i < list.length; i++) { let productDetails = list[i]; if (window._ltk) { window._ltk.SCA.AddItemWithLinks(productDetails.sku, productDetails.qty, productDetails.price, productDetails.name, productDetails.customAttributes.image, productDetails.customAttributes.urlKey); window._ltk.SCA.Submit(); console.log("listrak add to cart event called ", productDetails.sku, productDetails.qty, productDetails.price, productDetails.name, productDetails.customAttributes.image, productDetails.customAttributes.urlKey); } } console.log("view basket", items); }; export const listrakCartListClear = () => { if (window._ltk) { window._ltk.SCA.ClearCart(); } console.log("listrak Clear Cart called"); }; export const googleAanalyticsPurchase = (resp, incrementId) => { let items = []; let purchasedProductList = []; for (let i = 0; i < resp.items.length; i++) { let item = resp.items[i]; let catName = ""; if (getCookieByName(item.quoteItemId)) { catName = getCookieByName(item.quoteItemId) catName = catName.split(':')[0]; removeCookieByName(item.quoteItemId) } else if (item.extensionAttributes["categoryLinks"]) { try { let categoryLink = JSON.parse(item.extensionAttributes["categoryLinks"][0]); catName = categoryLink.category_name; } catch (error) { console.log("error", error); } } items.push({ 'id': item.sku, 'name': item.name, 'category': catName, 'brand': getlabelValuePurchase(item.extensionAttributes.customAttributes), 'price': item.price, 'quantity': item.qtyOrdered }) purchasedProductList.push( { id: item.productId, price: item.price, quantity: item.qtyOrdered } ); } // let gtag = window.gtag ? window.gtag : null; // if (gtag) { // gtag('event', 'purchase', { // 'transaction_id': incrementId, // 'affiliation': 'Crane', // 'value': resp.baseSubtotal, // 'tax': resp.taxAmount, // 'shipping': resp.shippingInclTax, // 'coupon': resp.couponCode ? resp.couponCode : '', // "items": items // }); // } window.dataLayer = window.dataLayer || []; window.dataLayer.push({ 'event': 'purchase', 'ecommerce': { 'purchase': { "actionField": { "id": incrementId, "affiliation": "Crane", "revenue": resp.baseSubtotal, "tax": resp.taxAmount, "shipping": resp.shippingInclTax, 'coupon': resp.couponCode ? resp.couponCode : '' }, 'products': items } } }); // window.dataLayer.push({ // 'event': 'purchase', // 'ecommerce': { // 'purchase': { // "actionField": { "id": incrementId, "affiliation": "Crane", "revenue": resp.baseSubtotal, "tax": resp.taxAmount, "shipping": resp.shippingInclTax, 'coupon': resp.couponCode ? resp.couponCode : '' }, // 'transaction_id': incrementId, // 'affiliation': 'Crane', // 'value': resp.baseSubtotal, // 'tax': resp.taxAmount, // 'shipping': resp.shippingInclTax, // 'coupon': resp.couponCode ? resp.couponCode : '', // 'items': items // } // } // }); // let dlObjects = [{ // "pageName": "Success Page", // "pageType": "purchase", // "ecommerce": { // "purchase": { // "actionField": { "id": incrementId, "affiliation": "Crane", "revenue": resp.baseSubtotal, "tax": resp.taxAmount, "shipping": resp.shippingInclTax, 'coupon': resp.couponCode ? resp.couponCode : '' }, // "products": items // }, // "currencyCode": resp.orderCurrencyCode // } // }]; // console.log("dlObjects", dlObjects); // for (let i in dlObjects) { // window.dataLayer.push(dlObjects[i]); // } //criteo tag - purchase order window.criteo_q.push( { event: "trackTransaction", id: incrementId, item: purchasedProductList }); // let purchasedDlObjects = { // "pageType": "TransactionPage", // "ProductBasketProducts": purchasedProductList, // "TransactionID": incrementId // } // window.dataLayer.push(purchasedDlObjects); console.log("criteo track transaction ", purchasedProductList); console.log("Track transaction id ", incrementId); if (window._ltk) { window._ltk.Order.SetCustomer(resp.customerEmail, resp.customerFirstname, resp.customerLastname); window._ltk.Order.OrderNumber = incrementId; window._ltk.Order.ItemTotal = resp.baseSubtotal; window._ltk.Order.ShippingTotal = resp.shippingInclTax; window._ltk.Order.TaxTotal = resp.baseTaxAmount; window._ltk.Order.HandlingTotal = '0.00'; window._ltk.Order.OrderTotal = resp.baseGrandTotal; for (let i = 0; i < resp.items.length; i++) { let item = resp.items[i]; window._ltk.Order.AddItem(item.sku, item.qtyOrdered, item.price); // one line per item ordered } window._ltk.Order.Submit(); console.log("listrak purchased event called", resp); window._ltk.SCA.Update("email", resp.customerEmail); console.log("listrak email event called", resp.customerEmail); window._ltk.SCA.ClearCart(); } } export const getCatPath = async (catId) => { let path = ''; let categoryDetailsList = window.craneCatalog; let categoryOne = await getCategoryOne( categoryDetailsList.allCategoryDetails, Number(catId) ); if (categoryOne) { path = categoryOne.n; } return path; } export const googleAanalyticsEventPDP = async (productDetails, action, categoryId) => { let catName = ''; if (categoryId) { catName = await getCatPath(categoryId); } else { if (productDetails.extensionAttribute.catagoryLinks[0]) { let catId = productDetails.extensionAttribute.catagoryLinks[0].catagoryId; catName = await getCatPath(catId); } } let gtag = window.gtag ? window.gtag : null; if (gtag) { gtag('event', action, { 'event_category': "ecommerce", "items": [{ 'id': productDetails.sku, 'name': productDetails.name, 'category': catName, 'brand': getlabelValue(productDetails.customAttribute, "brand"), //'price': productDetails.price, //'quantity': qtyNew }] }); } console.log("google analytics event called ", action, categoryId, catName); if (window._ltk) { window._ltk.Activity.AddProductBrowse(productDetails.sku); console.log("listrak event called ", productDetails.sku); } } export const listrakEmailCapture = (email) => { if (window._ltk) { window._ltk.SCA.Update("email", email) console.log("listrak email event called ", email); } } export const googleAanalyticsEvent = (action, category, productDetails) => { let gtag = window.gtag ? window.gtag : null; if (gtag) { gtag('event', action, { 'event_category': category, 'event_label': productDetails.name, 'value': productDetails.sku }); } console.log("google analytics event called ", action); } export const googleAanalyticsCheckoutAddPaymentInfo = (action, options) => { let gtag = window.gtag ? window.gtag : null; if (gtag) { let itemList = [] for (let i = 0; i < options.items.length; i++) { itemList.push({ "item_id": options.items[i].sku, "item_name": options.items[i].name, //"coupon": listName, //"discount": options[i].b, //"affiliation": category, //"item_brand": options[i].customAttributes.brand, //"item_category": productPrice, //"item_variant":options[i].customAttributes.color, "price": options.items[i].price, "currency": 'USD', "quantity": options.items[i].qtyOrdered }) } gtag('event', 'checkout_progress', { "checkout_step": 3, "checkout_option": "payment_method", "value": 1, items: itemList }); } console.log("google analytics called ", action); } export const googleAanalyticsCheckoutAddShippingInfo = (action, options) => { let gtag = window.gtag ? window.gtag : null; if (gtag) { let itemList = [] for (let i = 0; i < options.length; i++) { itemList.push({ "item_id": options[i].sku, "item_name": options[i].name, "price": options[i].price, "currency": 'USD', "quantity": options[i].qty }) } gtag('event', 'checkout_progress', { "checkout_step": 2, "checkout_option": "shipping method", "value": 3, items: itemList }); } console.log("google analytics called ", action); } export const googleAanalyticsEventCategoryPage = async (productDetails, categoryId) => { let gtag = window.gtag ? window.gtag : null; let category = '' let listName = '' if (categoryId) { listName = "Category Results" category = await getCatPath(categoryId) } else { listName = "Search Results" category = "Search" } if (gtag) { let itemList = [] for (let i = 0; i < productDetails.length; i++) { let productPrice = '' if (productDetails[i].lp) { productPrice = productDetails[i].lp } else { if (productDetails[i].sp) { productPrice = roundUp(productDetails[i].sp) } else if (productDetails[i].p != 0) { productPrice = productDetails[i].p } } itemList.push({ "id": productDetails[i].sku, "name": productDetails[i].n, "list_name": listName, "brand": productDetails[i].b, "category": category, "variant": productDetails[i].dc, //"list_position": 1, //"quantity": 2, "price": productPrice }) } if (itemList.length > 0) { gtag('event', 'view_item_list', { "event_category": "ecommerce", "items": itemList }); } } /*let category='' if(categoryId) { category =await getCatPath(categoryId) }else{ category ="search" } if(category){ window.dataLayer = window.dataLayer || []; window.dataLayer.push({ 'event':'productFilter', 'eventCategory':category, 'eventAction':action, 'eventLabel':label, 'eventValue':value }); }*/ console.log("google analytics event category ", window.dataLayer); } export const googleAanalyticsCheckout = (action, options) => { let gtag = window.gtag ? window.gtag : null; if (gtag) { gtag('event', action, { ...options }); } console.log("google analytics called ", action); } export const googleAanalyticsEventCategory = (action, category, categoryDetails) => { let gtag = window.gtag ? window.gtag : null; if (gtag) { gtag('event', action, { 'event_category': category, 'event_label': categoryDetails.name, 'value': categoryDetails.id }); } console.log("google analytics event called ", { 'event_category': category, 'event_label': categoryDetails.name, 'value': categoryDetails.id }); } export const listrakSubscribe = async (email) => { if (window._ltk) { window._ltk.Subscriber.List = "Footer"; window._ltk.Subscriber.Email = email; // window._ltk.Subscriber.Profile.Add("CheckBox.Source.Product Registrations", "on"); window._ltk.Subscriber.Submit(); } } export const checkEncodeURI = (str) => { try { decodeURIComponent(escape(window.atob(str))); return true; } catch (e) { return false; } } export const priceFormatter = (price, pdp) => { if (price != undefined) { price = price.toString(); let decimals = (price.split("."))[1]; if ((!Number(decimals) || isNaN(decimals)) || decimals.length == 1) //if 2 or 2.1 return Number(price).toFixed(2); if (decimals.length == 2 && pdp) //if 2 or 2.1 return price; else if (decimals.length > 1) // if 2.34 or 2.56565 return Number(price.match(/^-?\d+(?:\.\d{0,2})?/)[0]); } } export const invalidPoBoxAddress = (address) => { let containedPoBox = false; let addressNew = address.toLowerCase(); if (addressNew.search("po box") > -1) containedPoBox = true; else if (addressNew.search("pobox") > -1) containedPoBox = true; else if (addressNew.search("post office") > -1) containedPoBox = true; else if (addressNew.search("postoffice") > -1) containedPoBox = true; else if (addressNew.search("post office box") > -1) containedPoBox = true; else if (addressNew.search("postofficebox") > -1) containedPoBox = true; else if (addressNew.search("p.o.box") > -1) containedPoBox = true; else if (addressNew.search("p.o. box") > -1) containedPoBox = true; else if (addressNew.search("p. o. box") > -1) containedPoBox = true; else if (addressNew.search("p o box") > -1) containedPoBox = true; else containedPoBox = false; return containedPoBox; } export const getProductArray = (productData, categoryId) => { if (productData.allCategoryDetails) { let result = productData.allCategoryDetails.filter(element => { return element.id === categoryId; }); if (result[0]) return result[0].p; else return ''; } } export const getProductsList = (productData, productArray) => { let productList = []; if (productData.products) { for (let i = 0; i < productArray.length; i++) { productData.products.filter(element => { if (element.sku === productArray[i]) { productList.push(element); } }); } return productList; } } /* eslint-disable */ export const checkPromotion = ({ sku, quantity, product, productPartsObjects }) => { for (let i = 0; i < promotions.length; i++) { let promotion = promotions[i]; let rules = promotion.promotion_rule; promotion.appliedRules = []; promotion.exclusive = []; promotion.exclusiveRules = []; for (let m = 0; m < rules.length; m++) { let rule = rules[m]; let conditions = rule.conditions; rule.allCondition = false; if (rule.rule_type == "exclusive") promotion.exclusive.push("true"); rule.evaluateConditions = []; for (let j = 0; j < conditions.length; j++) { let condition = conditions[j]; switch (condition.variable) { case "product_sku": rule.allCondition = evaluatePredicate(condition.predicate, (condition.value.toLowerCase()), sku.toLowerCase()); break; case "product_tag": let tags = condition.value.split(','); if (product.tags) { const found = tags.some(r => product.tags.indexOf(r) >= 0) if (found) rule.allCondition = true else rule.allCondition = false; } break; case "quantity": rule.allCondition = evaluatePredicate(condition.predicate, condition.value, quantity); break; case "Product_part_with_liner": let partName = condition.sub_variable; let objects = productPartsObjects.filter((obj) => obj.partName.toLowerCase() == partName.toLowerCase())[0]; if (objects && objects.linerObject && objects.linerObject.selectedLiner) { rule.allCondition = true } else rule.allCondition = false; break; case "count_of_product_part_press_passes": let name = condition.sub_variable; let partObjects = productPartsObjects.filter((obj) => obj.partName.toLowerCase() == name.toLowerCase())[0]; if (partObjects && partObjects.processes) { let processes = partObjects.processes; if (Object.keys(processes).length) rule.allCondition = evaluatePredicate(condition.predicate, condition.value, processes[Object.keys(processes)[0]].passes); else rule.allCondition = evaluatePredicate(condition.predicate, condition.value, 0);; } else rule.allCondition = false; break; case "count_of_product_press_passes": let passes = 0; let processesObject = {}; for (let k = 0; k < productPartsObjects.length; k++) { let partObjects = productPartsObjects[k]; if (partObjects.processes) { let processes = partObjects.processes; for (const [key, value] of Object.entries(processes)) { if (!processesObject.hasOwnProperty(key)) { processesObject[key] = []; } for (let p = 0; p < value.colors.length; p++) { let color = value.colors[p]; if (!processesObject[key].includes(color)) { passes = passes + 1; processesObject[key].push(color); } } } } } rule.allCondition = evaluatePredicate(condition.predicate, condition.value, passes); break; } rule.evaluateConditions.push(rule.allCondition); } if (rule.evaluateConditions.length > 0 && !rule.evaluateConditions.includes(false)) { promotion.appliedRules.push(rule); promotion.applied = true; if (rule.rule_type == "exclusive") { promotion.exclusiveRules.push("true"); } } } } return promotions.filter(promotion => { return (promotion.applied === true && (promotion.exclusiveRules.length == promotion.exclusive.length)) })[0]; } export const evaluatePredicate = (operator, compareValue, value) => { let boolean = true; switch (operator) { case ">": if (Number(value) > Number(compareValue)) boolean = true; else boolean = false break; case "<": if (Number(value) < Number(compareValue)) boolean = true; else boolean = false break; case "<=": if (Number(value) <= Number(compareValue)) boolean = true; else boolean = false break; case ">=": if (Number(value) >= Number(compareValue)) boolean = true; else boolean = false break; case "==": if (Number(value) == Number(compareValue)) boolean = true; else boolean = false break; case "=": if (Number(value) === Number(compareValue)) boolean = true; else boolean = false break; case "IN": let values = (compareValue.toLowerCase()).split(','); if (values.includes(value.toLowerCase())) boolean = true; else boolean = false break; } return boolean; } export const setCategoryNameInLocal = async (categoryId, res) => { let categoryDetailsList = window.craneCatalog; let categoryOne = await getCategoryOne( categoryDetailsList.allCategoryDetails, Number(categoryId) ); if (categoryOne && res) { window.$cookies.set(res.item_id, categoryOne.n + ':' + categoryId, '30d', null, getDomain(window.location.hostname)); } console.log('category name ', res.item_id, categoryOne.n); } export const getName = (label) => { const filterList = [{ name: "brand", label: "b" }, { name: "color_parent", label: "dc" }, { name: "design_style", label: "ds" }, { name: "occasion", label: "o" }, { name: "paper_color_parent", label: "pc" }, { name: "paper_weight", label: "pw" }, { name: "personalized", label: "per" } , { name: "photo_card", label: "ph" }, { name: "printing_process", label: "pm" }, { name: "product_def_type", label: "pt" }, { name: "uom", label: "u" } ]; let name = filterList.filter((item) => item.label == label) if (name) { return name[0].name } } export const roundUp = (num) => { var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]; return with2Decimals; }