kingdiao / amazon SC Find Order for Customer

// ==UserScript==
// @name         amazon SC Find Order for Customer
// @namespace    http://tampermonkey.net/
// @version      1
// @description  Adds a button to amazon Seller Central Messages Inbox to find buyers by email address
// @author       rin
// @license      MIT
// @match        http*://sellercentral.amazon.com/messaging/inbox/*
// @match        http*://sellercentral.amazon.ca/messaging/inbox/*
// @match        http*://sellercentral.amazon.com.mx/messaging/inbox/*
// @match        http*://sellercentral-europe.amazon.com/messaging/inbox/*
// @match        http*://sellercentral.amazon.co.uk/messaging/inbox/*
// @match        http*://sellercentral.amazon.de/messaging/inbox/*
// @match        http*://sellercentral.amazon.es/messaging/inbox/*
// @match        http*://sellercentral.amazon.it/messaging/inbox/*
// @match        http*://sellercentral.amazon.fr/messaging/inbox/*
// @match        http*://sellercentral.amazon.co.jp/messaging/inbox/*
// @match        http*://sellercentral.amazon.in/messaging/inbox/*
// @grant        none
// ==/UserScript==

(function () {
  'use strict';

  var options = {
    buyerEmailContainerId: 'threadBuyerProxyEmail',
    orderInfoContainerId: 'dynamic-context'
  };

  var buttonOptions = {
    listBaseUrl: '/gp/orders-v2/list/ref=ag_myo_apsearch_myosearch?',
    label: '🔎Find Order',
    buttonContainerElement: 'div',
    containerId: 'links-wrap'
  };

  var encodeParams = function (params) {
    var esc = encodeURIComponent;
    var query = Object.keys(params)
      .map(key => esc(key) + '=' + esc(params[key]))
      .join('&');
    return query;
  };

  var getBuyerEmail = function (buyerEmailContainerId) {
    return document.getElementById(buyerEmailContainerId).innerText;
  };

  var searchUrl = function (buttonOptions, buyerEmail) {
    var searchParams = {
      searchType: 'BuyerEmail',
      preSelectedRange: '365',
      searchDateOption: 'preSelected',
      searchKeyword: buyerEmail
    };
    return buttonOptions.listBaseUrl + encodeParams(searchParams);
  };

  var addButton = function (buttonOptions, buyerEmail) {
    var button = document.createElement('a');
    button.setAttribute('href', searchUrl(buttonOptions, buyerEmail));
    button.append(buttonOptions.label);
    var buttonContainer = document.createElement(buttonOptions.buttonContainerElement);
    buttonContainer.appendChild(button);
    document.getElementById(buttonOptions.containerId).appendChild(buttonContainer);
  };

  var orderInfoMissing = document.getElementById(options.orderInfoContainerId).childElementCount <= 1;
  if (orderInfoMissing) {
    var buyerEmail = getBuyerEmail(options.buyerEmailContainerId);
    addButton(buttonOptions, buyerEmail);
  }
})();