e14matt / CPC Staff Prices

// ==UserScript==
// @name            CPC Staff Prices
// @namespace       https://cpc.co.uk
// @include         http://cpc.farnell.com/*
// @include         https://cpc.farnell.com/*
// @description     Script to show staff prices inline -- won't work unless you're an employee on the company network. Written by Matt Collinge.
// @require         http://code.jquery.com/jquery-latest.js
// @copyright       Matt Collinge
// @author          e14matt
// @license MIT
// @grant           GM_xmlhttpRequest
// @connect         ontrack.premierfarnell.net
// @updateURL       https://openuserjs.org/meta/e14matt/CPC_Staff_Prices.meta.js
// @version         2.6
// ==/UserScript==

// GUID = 64a6bc68-0d6a-4df1-a22f-18ab15ff265f

//debugger;


const observer = new MutationObserver(() => {
    injectStaffPrice();
});

// Observe the minimum safe scope
observer.observe(document.body, {
    childList: true,
    subtree: true
});

function injectStaffPrice() {
    // Select the TotalPrice element
    const totalPriceEl = document.querySelector('[class^="PdpAddToBasketstyles__TotalPrice"]');
    if (!totalPriceEl) return;

    // Prevent duplicate injection
    if (document.getElementById('staffPrice')) return;

    // Get the SKU from the URL
    var productCode = window.location.pathname.split('/')[window.location.pathname.split('/').length-1]
    console.log('Staff price tool found SKU: '+productCode);

    if(productCode!=='') {
        $('<p id="staffPrice" style="padding-top:2px"><font color="green" size="2">Fetching staff price...</font></p>').insertAfter('[class*="PdpAddToBasketstyles__TotalPrice"]');
        retrieveStaffPrice(productCode);
    }
}

function retrieveStaffPrice(productCode) {

    console.log('Fetching staff price for '+productCode);
	GM_xmlhttpRequest({
		method: 'GET',
		url: 'http://ontrack.premierfarnell.net/cpc/indexAPI.php?find='+productCode+'&mode=search',
		headers: {
			'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
			'Accept': 'application/atom+xml,application/xml,text/xml',
		},
		onload: function(responseDetails) {
			var responseJSON = $.parseJSON(responseDetails.responseText);
			if (responseJSON.count=='0') {
				$('#staffPrice').html('Unable to find staff price for this item ('+productCode+')');
			} else {
				$('#staffPrice').html('<font color="green" size="2"><b>Staff Price: </b>£' + responseJSON.items[0].priceIncVat + ' inc VAT <a href="http://ontrack.premierfarnell.net/cpc/index.php?find='+productCode+'&mode=search" title="Staff price page" style="padding-left:2px;" target="_blank">🔗‍️</a></font>');
			}
		}
	});

}