macheteYeti / LWAF Named SMS Contacts

// ==UserScript==
// @name         LWAF Named SMS Contacts
// @namespace    SUD
// @license MIT
// @include https://inbox.helpwise.io/inboxes/*
// @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
// @downloadURL https://openuserjs.org/install/macheteYeti/LWAF_Named_SMS_Contacts.user.js
// @updateURL https://openuserjs.org/install/macheteYeti/LWAF_Named_SMS_Contacts.user.js
// @version 9
// @grant GM_addStyle
// @author       macheteYeti
// @license MIT
// @description  Adds functionality to replace phone numbers with names in Helpwise SMS inbox
// ==/UserScript==

$(document).ready(function(){

	if(window.location.href.indexOf('230894')>-1){
	
		phones=$.ajax({type:'GET',url:"https://members.livewellandfully.com/sud/phones.php",async:false,dataType:'json',data:{type:'phones'},fail:function(jqXHR,textStatus,errorThrown){console.log('Could not get items, server response: '+textStatus+': '+errorThrown);}}).responseJSON;
		
		$(document).arrive(".thread-addr-main",function(){
		
			if(typeof phones[$(this).text().trim()]!=typeof undefined)$(this).text(phones[$(this).text().trim()])
		});
		$(document).arrive("#thread-subject",function(){
		
			if(typeof phones[$(this).text().trim()]!=typeof undefined)$(this).text(phones[$(this).text().trim()]);
		});
		$(document).arrive("#broad-thread .text-truncate span",function(){
		
			if(typeof phones[$(this).text().trim()]!=typeof undefined)$(this).text(phones[$(this).text().trim()]);
		});
	}
	else{
	
		$(document).arrive(".thread-addr-main",function(){
		
			if($(this).text().trim()=="")$(this).text("<no subject>");
		});
		$(document).arrive("#thread-subject",function(){
		
			if($(this).text().trim()=="")$(this).text("<no subject>");
		});
		$(document).arrive("#broad-thread .text-truncate span",function(){
		
			if($(this).text().trim()=="")$(this).text("<no subject>");
		});
	}
	
	var excludes=['Support','Sunnybelle Sevilleno','Mary Panaligan','Jacque Mortenson','Patti Franco','Barbara Decker','Yeti &quot;Eric&quot; Decker','Barbara Decker','Jonalyn Jabinez-Pitogo'];
	
	function extractEmails(elementSelector){
	
		const text = $(elementSelector).text();
		const emailRegex = /[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+/gi;
		const emails = [...new Set(text.match(emailRegex))];
		return emails || [];
	}
	
	$(document).arrive('.email-addresses strong',function(){
	
		if($(this).parents('.email-addresses').find('strong').length<2)return false;
		
		email="";
		$.each(extractEmails($(this).parents('.email-addresses')),function(i,v){
		
			console.log(i+', '+v);
			if(v!='support@livewellandfully.com')email=v;
			if(i==1)return false;
		});
		
		stud="";
		$('body').find('div[id*="email-content"]').each(function(){
		
			if($.inArray($(this).first().find('strong').first().text().trim(),excludes)==-1){
			
				console.log('using '+$(this).first().find('strong').first().text().trim());
				stud=$(this).first().find('strong').first().text().trim();
			}
		});
		
		var t=$('.mail-content-header');
		$.ajax({type:'GET',url:"https://members.livewellandfully.com/sud/phones.php",async:false,dataType:'json',data:{type:'student',student:stud,email:email},fail:function(jqXHR,textStatus,errorThrown){console.log('Could not get items, server response: '+textStatus+': '+errorThrown);},success:function(d){
		
			// if(!t.hasClass('programmed'))$("<ul class='programs'></ul>").insertAfter(t.find('div').first().find('div').first().children().first());
			if(!t.hasClass('programmed'))$("<section id='studentDets'><ul class='programs'></ul></studentDets>").insertBefore(t);
			else return false;
			
			if($('#tags-list').length)$('.programs').addClass('tagged');
			
			var linkable=false;
			$.each(d.progs,function(i,v){
			
				var classes='';
				if(v=='none found'||v=='ambiguous email'){
				
					t.parent().find('.programs').append("<li class='notfound' title='notify yeti if you think this student should have programs listed'>"+v+"</li>");
				}
				else if(v=='name/email mismatch'){
				
					t.parent().find('.programs').append("<li class='notfound' title='the student did not write in from their registered email'>"+v+"</li>");
				}
				else{
				
					$.each(v,function(k,w){classes+=w+" "});
					t.parent().find('.programs').append("<li class='"+classes.trim()+"' title='"+classes.trim()+"'>"+i+"</li>");
					console.log('outputting '+i);
					linkable=true;
				}
			});
			t.addClass('programmed');
			if(!t.hasClass('buttoned')&&d.acid.toString().length>0){
			
				$('<button class="acRecord" data-id="'+d.acid+'">Open AC Record</button>').insertBefore($('.programs'));
				if(d.progs[0]!='none found'&&d.progs[0]!='name/email mismatch')$('<button class="tcRecord" data-id="'+d.email+'">Open ThriveCart</button>').insertBefore($('.programs'));
				t.addClass('buttoned');
			}
		}});
	});
	$(document).on('click','.acRecord',function(e){
	
		e.preventDefault();
		window.open("https://livewellandfully.activehosted.com/app/contacts/"+$(this).attr('data-id'));
	});
	$(document).on('click','.tcRecord',function(e){
	
		e.preventDefault();
		window.open("https://thrivecart.com/livewellandfully/#/orders?searchCust="+$(this).attr('data-id'));
	});
});

GM_addStyle( `
   .programs{list-style-type:none;margin:1.2em 0 0 .7em;padding:0}
   .programs.tagged{margin-top:.8em}
   .programs+.programs{display:none}
   .programmed{float:left;margin-right:1em}
   .programs li{display:inline;margin-right:.5em;border:1px solid black;padding:2px 5px;border-radius:1em}
   .programs li.inactive{background-color:#ccc}
   .programs li.active{background-color:#5b792f;color:#fff}
   .programs li.purchased,.programs li.purchase{background-color:#0a4d7a;color:#fff}
   .programs li.notfound{background-color:#ab4129;color:#fff}
   .acRecord{background-color: #de6b0b;color: #fff;margin: .5em;height: 2em;border-radius: 1em;}
   .tcRecord{background-color: #bc7712;color: #fff;margin: .5em;height: 2em;border-radius: 1em;}
   #studentDets{display:flex}
` );