macheteYeti / LWAF Retrieve TC Products

// ==UserScript==
// @name         LWAF Retrieve TC Products
// @namespace    SUD
// @license MIT
// @include https://thrivecart.com/livewellandfully*
// @include https://thrivecart.com/loveanotherway*
// @require http://code.jquery.com/jquery-3.4.1.min.js
// @require     https://cdnjs.cloudflare.com/ajax/libs/arrive/2.4.1/arrive.min.js
// @version 16
// @grant GM_addStyle
// @author       macheteYeti
// @description  Monitors ThriveCart products and permits opening all in tabs
// ==/UserScript==

$(document).ready(function(){

	// AC Link Feature
	var acCache = {};
	var acCacheLoaded = false;

	function loadACCache(callback){
		$.ajax({
			type: 'GET',
			url: 'https://members.livewellandfully.com/sud/acLookup.php',
			dataType: 'json',
			success: function(d){
				if(d.success && d.data){
					acCache = d.data;
				}
				acCacheLoaded = true;
				if(callback) callback();
			},
			error: function(){
				acCacheLoaded = true;
				if(callback) callback();
			}
		});
	}

	function processACLink($acLink, email){
		if(acCache[email]){
			$acLink.attr('title', 'View in ActiveCampaign').css('cursor','pointer').on('click', function(e){ e.preventDefault(); window.open('https://livewellandfully.activehosted.com/app/contacts/' + acCache[email]); });
			return;
		}
		$.ajax({
			type: 'GET',
			url: 'https://members.livewellandfully.com/sud/acLookup.php',
			data: {email: email},
			dataType: 'json',
			success: function(d){
				if(d.success){
					$acLink.attr('title', 'View in ActiveCampaign').css('cursor','pointer').on('click', function(e){ e.preventDefault(); window.open(d.url); });
					acCache[email] = d.id;
				} else {
					$acLink.addClass('ac-not-found').attr('title', 'Not in AC');
				}
			},
			error: function(){
				$acLink.addClass('ac-error').attr('title', 'AC lookup failed');
			}
		});
	}

	function addACLinks(){
	if(!acCacheLoaded){
		loadACCache(addACLinks);
		return;
	}
	
	// Order list rows
	$('.order-list-purchase').each(function(){
		var $row = $(this);
		if($row.hasClass('ac-processed')) return;
		$row.addClass('ac-processed');
		var $emailEl = $row.find('.order-row-customer-email a');
		var $actionCol = $row.find('.order-column-action');
		if($emailEl.length === 0 || $actionCol.length === 0) return;
		var email = $emailEl.text().trim().toLowerCase();
		
		// Helpwise button
		var $hwLink = $('<a class="pure-button button-xsmall button-subtle hw-link" href="https://inbox.helpwise.io/inboxes/206907/mine?search='+email+'" target="_blank" title="Search in Helpwise"><i class="fa fa-fw fa-life-ring"></i></a>');
		$actionCol.prepend($hwLink);
		
		// AC button
		var $acLink = $('<a class="pure-button button-xsmall button-subtle ac-link" href="#" target="_blank" title="Loading..."><i class="fa fa-fw fa-address-book"></i></a>');
		$actionCol.prepend($acLink);
		processACLink($acLink, email);
	});
	
	// Individual customer page
	$('.ui-personal-block').each(function(){
		var $block = $(this);
		if($block.hasClass('ac-processed')) return;
		$block.addClass('ac-processed');
		var $emailEl = $block.find('.ui-customer-email a');
		var $info = $block.find('.info');
		if($emailEl.length === 0 || $info.length === 0) return;
		var email = $emailEl.text().trim().toLowerCase();
		
		// Helpwise button
		var $hwLink = $('<a class="pure-button button-outline button-subtle hw-link-profile" href="https://inbox.helpwise.io/inboxes/206907/mine?search='+email+'" target="_blank" title="Search in Helpwise"><i class="fa fa-life-ring"></i> Helpwise</a>');
		$info.append($hwLink);
		
		// AC button
		var $acLink = $('<span class="pure-button button-outline button-subtle ac-link-profile"><i class="fa fa-address-book"></i> AC</span>');
		$info.append($acLink);
		processACLink($acLink, email);
	});
}

	loadACCache(function(){
		addACLinks();
	});

	$(document).arrive('.order-list-purchase', function(){
		addACLinks();
	});

	// Fallbacks for SPA navigation
	$(window).on('hashchange', function(){
		setTimeout(addACLinks, 300);
	});

	setInterval(function(){
		if($('.ui-personal-block:not(.ac-processed)').length > 0 || $('.order-list-purchase:not(.ac-processed)').length > 0){
			addACLinks();
		}
	}, 1000);
	
	poppedState=0;
	
	function getID(){
	
		var urlparts=window.location.href.split('/');
		urlparts.reverse();
		var id=0;
		for(i in urlparts){
		
			if(!isNaN(urlparts[i])){
			
				id=urlparts[i];
				break;
			}
		}
		return id;
	}
	function getBrand(){ return window.location.href.indexOf('loveanotherway')>-1?'loveanotherway':'livewellandfully'; }
	// $(document).on('click','.ui-icon-clone',
	function doIt(){
	
		if(window.location.href.indexOf('/products')>-1){
		
			$(document).arrive('.box-list-product-row',function(){
			
				console.log('revealing product url');
				if($(this).hasClass('urled'))return false;
				
				var dets=$.parseJSON($(this).attr('data-product'));
				var url=dets['_link_upsell'].split("/upsell")[0];
				$('<span class="list-product-url"><a target="_blank" href="'+url+'">'+url.split('/').pop()+'</a></span>').insertAfter($(this).find('.list-product-date'));
				
				$(this).addClass('urled');
			});
		}
		
		else if(window.location.href.indexOf('/behavior')>-1){
		
			prod=getID();
			autoing='list';
			autos=[];
			
			$(document).arrive('.ui-product-settings-tab-customers-options-wrapper+.pure-controls',function(){
			
				outputSave();
			});
			function outputSave(){
			
				$(this).find('.ui-ctrl-btn-nav.ui-ctrl-btn-save.pure-button.button-primary').css('display','none').attr('id','tcSave');
				console.log('adding button');
				if($('#saveAutos').length==0)$('<button id="saveAutos">Save Automation Data</button>').insertBefore($('.ui-ctrl-btn-nav.ui-ctrl-btn-save.pure-button.button-primary').last());
			}
			setTimeout(()=>{
			
				outputSave();
			},1000);
			$(document).on('click','#saveAutos',function(e){
			// $(document).on('click','.ui-ctrl-btn-nav.ui-ctrl-btn-save.button-primary',function(){
			
				e.preventDefault();
				e.stopPropagation();
				e.stopImmediatePropagation();
				
				console.log('do we have this?');
				$('.ui-autoresponder-block').each(function(){
				
					if($(this).attr('data-subtype')=='automation'&&$.inArray($(this).attr('data-action'),['bump','purchase'])>-1){
					
						autos.push({auto:$(this).find('.generic-list-aside').text(),action:$(this).attr('data-action')});
					}
				});
				console.log(autos);
				$(this).fadeOut();
				if(typeof autos!=typeof undefined){
				
					if(autos.length>0){
					
						$.ajax({type:'POST',crossDomain:true,cache:false,dataType:'json',url:"https://members.livewellandfully.com/sud/grabProductNew.php",data:{type:'autos',prod:prod,autos:autos,brand:getBrand()},success:function(d){
						
							if(d.success)$('.ui-product-settings-tab-customers-options-wrapper+.pure-controls').find('.ui-ctrl-btn-nav.ui-ctrl-btn-save.pure-button.button-primary').fadeIn();
							else alert('could not find automation by name, please try again');
						}
						});
						autos=[];
						editIndex=0;
					}
				}
				else $('#tcSave').fadeIn();
				
				return false;
			});
		}
		else if(window.location.href.indexOf('/orders')>-1&&window.location.href.indexOf('searchCust')>-1&&!poppedState){
		
			console.log('have cust to search');
			setTimeout(()=>{
				
					$('#history-list-filters-search-query').val(window.location.href.split('?searchCust=').pop());
					$('#history-list-filters-refine-date').val('all');
					setTimeout(()=>{$('#history-list-search')[0].click();},500);
				},1500);
			$(document).arrive('#history-list-filters-search-query',function(){
			
				setTimeout(()=>{
				
					console.log('have search field '+window.location.href.split('?searchCust=').pop());
					$(this).val(window.location.href.split('?searchCust=').pop());
					$('#history-list-filters-refine-date').val('all');
					setTimeout(()=>{$('#history-list-search')[0].click();},500);
				},1500);
			});
		}
		
		prod=getID();
		var urlparts=window.location.href.split('/');
		urlparts.reverse();
		console.log(urlparts);
		
		if(urlparts.length>6){
		
			if(window.location.href.indexOf('orders')>-1)doOrders();
			else if(window.location.href.indexOf('products')>-1){
				console.log('getting label');
				var id=getID();
				$.ajax({type:'POST',crossDomain:true,cache:false,dataType:'json',url:"https://members.livewellandfully.com/sud/grabProductNew.php",data:{type:'lab',id:id,brand:getBrand()},success:function(d){$('title').html(d.tit);setTimeout(()=>{if(!$('#tcTit').length)$('#body').prepend('<h2 id="tcTit">'+d.tit+'</h2>');},1000);}});
			}
		}
		else{
		
			console.log('checking for '+"https://thrivecart.com/"+getBrand()+"/#/products");
			if(window.location.href=="https://thrivecart.com/"+getBrand()+"/#/products"){
			
				console.log('gathering product data');
				//gather product information
				$(document).arrive(".box-list-product-row",function(){ dat[$(this).attr('data-asset-id')]=$(this).attr('data-product'); });
				
				//pass to server
				setTimeout(()=>{ $.ajax({type:'POST',crossDomain:true,cache:false,async:false,dataType:'json',url:"https://members.livewellandfully.com/sud/grabProductNew.php",data:{type:'check',dat:dat,brand:getBrand()}});
				
					if($('#side').length==0){$('#body').prepend("<div id='side' style='display:none'><fieldset><label for='openLive'><input type='checkbox' id='openLive' checked value='2'> Live</label><label for='openTest'><input type='checkbox' id='openTest' value='1'> Test</label><label for='openDisabled'><input type='checkbox' id='openDisabled' value='3'> Disabled</label></fieldset><fieldset><label for='openBehavior'><input type='radio' checked name='type' id='openBehavior' value='/behavior/'> Behavior</label><label for='openProduct'><input type='radio' name='type' id='openProduct' value='/'> Product</label><label for='openCustomize'><input type='radio' name='type' value='/customize/' id='openCustomize'> Checkout</label></fieldset><a id='opener' class='pure-button button-primary button-small'>Open in Tabs</a></div>");$('#side').fadeIn('slow');}
					
					else{$('#side').fadeIn('slow');}
				},500);
			}
			else doOrders();
		}
		
		// Add this block inside the doIt() function
		
		function labelProducts(){
		
			console.log('labeling products in selector');
			
			$.ajax({
				type: 'POST',
				crossDomain: true,
				cache: false,
				dataType: 'json',
				url: "https://members.livewellandfully.com/sud/grabProductNew.php",
				data: {type: 'labs', brand: getBrand()},
				success: function(d){
					
					$('#stats-product-selector option').each(function(){
						
						if($(this).hasClass('labeled')) return;
						
						var prodId = $(this).val();
						if(prodId && d[prodId]){
							var currentText = $(this).text();
							$(this).text(currentText + ' | ' + d[prodId]);
							$(this).addClass('labeled');
						}
					});
				}
			});
		}

		// Check if already present
		if($('#stats-product-selector').length > 0){
			labelProducts();
		}

		// Also watch for it to arrive
		$(document).arrive('#stats-product-selector', function(){
			labelProducts();
		});
		
		var labeling = false;
		
		function labelProductList(){
		
			if(labeling) return;
			labeling = true;
			
			console.log('labeling products in list selector');
			
			$.ajax({
				type: 'POST',
				crossDomain: true,
				cache: false,
				dataType: 'json',
				url: "https://members.livewellandfully.com/sud/grabProductNew.php",
				data: {type: 'labs', brand: getBrand()},
				success: function(d){
					
					$('#stats-product-list').siblings('.nice-select').find('ul.list li').each(function(){
						
						if($(this).hasClass('labeled')) return;
						
						var val = $(this).attr('data-value');
						if(val && val.indexOf('product-') === 0){
							var prodId = val.replace('product-', '');
							if(d[prodId]){
								var currentText = $(this).text();
								var newText = currentText + ' | ' + d[prodId];
								$(this).html('<input type="checkbox" class="prod-check"> <span class="prod-text">' + newText + '</span>');
								$(this).addClass('labeled');
							}
						}
					});
					
					labeling = false;
				}
			});
		}
		
		$(document).arrive('#stats-product-list + .nice-select ul.list li[data-value^="product-"]', {onceOnly: false, existing: true}, function(){
			
			if($(this).hasClass('labeled')) return;
			
			console.log('product list item arrived');
			labelProductList();
		});
		
		$(document).on('click', '.nice-select ul.list li .prod-check', function(e){
			e.preventDefault();
			e.stopPropagation();
			e.stopImmediatePropagation();
			
			$(this).closest('li').click();
			
			setTimeout(function(){
				$('#stats-product-list').siblings('.nice-select').addClass('open');
			}, 10);
		});
	}
	function doOrders(){
	
		$('#side').fadeOut();
		
		if(window.location.href.indexOf('orders')>-1){
		
			console.log('found transactions page');
			$.ajax({type:'POST',crossDomain:true,cache:false,dataType:'json',url:"https://members.livewellandfully.com/sud/grabProductNew.php",data:{type:'labs',brand:getBrand()},success:function(d){
			
				// console.log(d);
				$(document).arrive('.order-list-purchase',function(){
				
					// console.log('checking '+$(this).find('.order-row-customer-name').text()+" "+$(this).find('.ui.order-invoice').length);
					// console.log('checking '+$(this).find('.ui-order-invoice').attr('data-product-id'));
					if($(this).find('.prod-link').length==1)return true;
					
					if($(this).find('.ui-order-invoice').length>0)var id=$(this).find('.ui-order-invoice').attr('data-product-id');
					else var id=$.parseJSON($(this).find('.ui-subscription-manage').attr('data-subscription-opts')).product_idx;
					
					var em=$(this).find('.order-row-purchase-name span em').text();
					$(this).find('.order-row-purchase-name span em').remove();
					$(this).find('.order-row-purchase-name span').html('<a href="https://thrivecart.com/livewellandfully/#/products/'+id+'">'+$(this).find('.order-row-purchase-name span').text()+'</a> <em>'+em+'</em>').addClass('prod-link');
				});
			}});
			
		}
	}
	$(document).arrive('#core-view-list-products',function(){
	
		doIt();
	});
	window.onpopstate=function(e){
	
		poppedState=1;
		console.log('popstate');
		
		doIt();
	}
	doIt();
	dat=[];
	wins=[];
	
	$(document).on('click','#opener',function(){
	
		if($(this).text()=='Open in Tabs'){
		
			var stati=[];
			$('#side fieldset').first().find('input').each(function(){
			
				if($(this).prop('checked')==true)stati.push($(this).val());
			});
			var type=$('#side input[name="type"]:checked').val().slice(0,-1);
			
			console.log("Opening "+type+" for "+stati.join(", ")+" products");
			$.ajax({type:'POST',crossDomain:true,cache:false,async:false,dataType:'json',url:"https://members.livewellandfully.com/sud/grabProductNew.php",data:{type:'opener',status:stati.join(", "),brand:getBrand()},success:function(dat){
			
				console.log(dat);
				$(dat[0]).each(function(k,v){
				
					wins.push(window.open("https://thrivecart.com/"+getBrand()+"/#/products/"+v+type));
					$('#opener').text('Close Tabs');
				});
			}});
		}
		else{
		
			for(i in wins)wins[i].close();
			$('#opener').text('Open in Tabs');
		}
	});
});

GM_addStyle( `
    #side{width:350px;height:189px;border:1px solid #ccc;position:absolute;left:-350px;font-size:1.3em;line-height:2;padding-top:1em}
	#side fieldset{margin-left:0;padding-left:1em;display:flex;justify-content:space-between}
	#opener{margin:1em;width:91%}
	.view-order-details-wrap .order-row-purchase-name-block{padding-bottom:.25em !important}
	.list-product-url{float:right;margin-bottom:5px;margin-top:-9px}
	.list-product-url a{color:#4591A9}
	#stats-product-list + .nice-select .nice-select-dropdown{min-width: 600px !important;}
	.nice-select ul.list li .prod-check{margin-right: 8px; cursor: pointer; width: 16px; height: 16px;}
	.nice-select ul.list li .prod-text{cursor: pointer;}
	.ac-link{margin-right:5px}
	.ac-link.ac-not-found,.ac-link-profile.ac-not-found{opacity:0.4;cursor:default;pointer-events:none}
	.ac-link.ac-error,.ac-link-profile.ac-error{color:#c33}
	.ac-link-profile{margin-left:5px;cursor:pointer}
` );